#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    2
    Rep Power
    0

    Help converting 'int' to 'str'


    Just a quick question that is probably very simple for some of you. I have been teaching myself python and have had a bit of trouble. I am trying to call a number to be displayed but I get the message
    'TypeError: Can't convert 'int' object to str implicitly'

    The extract of code is below:

    #user input defines hp - assume hp = 630
    Code:
        
        hp = int ( input ('Health Points: '))
        
        hpc = hp - 625
    
        if hp > 0:
            print ('HP is above average by ' + hpc)
    Thanks in advance for any help,

    TGSpike
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    4
    You can convert an int to a str by simply calling str() on it. However, there is no reason to do so in this case. You can simply pass multiple arguments to print(), which do not have to be strings, and it will separate them with spaces (by default):
    Code:
    print('HP is above average by', hpc)
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    2
    Rep Power
    0
    Originally Posted by Nyktos
    You can convert an int to a str by simply calling str() on it. However, there is no reason to do so in this case. You can simply pass multiple arguments to print(), which do not have to be strings, and it will separate them with spaces (by default):
    Code:
    print('HP is above average by', hpc)
    So all I need to do is change the '+ hpc) to ', hpc)? And will putting str (hpc) change it to a string? If it that simple then Thanks a lot! I have tried to hold out and work it out on my own but didn't realise how simpy it could be changed!
    Thanks again,

    TGSpike

IMN logo majestic logo threadwatch logo seochat tools logo