How to Concatenate Str and Int Objects

TypeError: cannot concatenate 'str' and 'int' objects

There are two ways to fix the problem which is caused by the last print statement.

You can assign the result of the str(c) call to c as correctly shown by @jamylak and then concatenate all of the strings, or you can replace the last print simply with this:

print "a + b as integers: ", c  # note the comma here

in which case

str(c)

isn't necessary and can be deleted.

Output of sample run:

Enter a: 3
Enter b: 7
a + b as strings: 37
a + b as integers: 10

with:

a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c

How can I concatenate str and int objects?

The problem here is that the + operator has (at least) two different meanings in Python: for numeric types, it means "add the numbers together":

>>> 1 + 2
3
>>> 3.4 + 5.6
9.0

... and for sequence types, it means "concatenate the sequences":

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> 'abc' + 'def'
'abcdef'

As a rule, Python doesn't implicitly convert objects from one type to another1 in order to make operations "make sense", because that would be confusing: for instance, you might think that '3' + 5 should mean '35', but someone else might think it should mean 8 or even '8'.

Similarly, Python won't let you concatenate two different types of sequence:

>>> [7, 8, 9] + 'ghi'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

Because of this, you need to do the conversion explicitly, whether what you want is concatenation or addition:

>>> 'Total: ' + str(123)
'Total: 123'
>>> int('456') + 789
1245

However, there is a better way. Depending on which version of Python you use, there are three different kinds of string formatting available2, which not only allow you to avoid multiple + operations:

>>> things = 5
>>> 'You have %d things.' % things  # % interpolation
'You have 5 things.'
>>> 'You have {} things.'.format(things)  # str.format()
'You have 5 things.'
>>> f'You have {things} things.'  # f-string (since Python 3.6)
'You have 5 things.'

... but also allow you to control how values are displayed:

>>> value = 5
>>> sq_root = value ** 0.5
>>> sq_root
2.23606797749979
>>> 'The square root of %d is %.2f (roughly).' % (value, sq_root)
'The square root of 5 is 2.24 (roughly).'
>>> 'The square root of {v} is {sr:.2f} (roughly).'.format(v=value, sr=sq_root)
'The square root of 5 is 2.24 (roughly).'
>>> f'The square root of {value} is {sq_root:.2f} (roughly).'
'The square root of 5 is 2.24 (roughly).'

Whether you use % interpolation, str.format(), or f-strings is up to you: % interpolation has been around the longest (and is familiar to people with a background in C), str.format() is often more powerful, and f-strings are more powerful still (but available only in Python 3.6 and later).

Another alternative is to use the fact that if you give print multiple positional arguments, it will join their string representations together using the sep keyword argument (which defaults to ' '):

>>> things = 5
>>> print('you have', things, 'things.')
you have 5 things.
>>> print('you have', things, 'things.', sep=' ... ')
you have ... 5 ... things.

... but that's usually not as flexible as using Python's built-in string formatting abilities.


1 Although it makes an exception for numeric types, where most people would agree on the 'right' thing to do:

>>> 1 + 2.3
3.3
>>> 4.5 + (5.6+7j)
(10.1+7j)

2 Actually four, but template strings are rarely used, and are somewhat awkward.


Other Resources:

  • Real Python: Splitting, Concatenating, and Joining Strings in Python
  • Python.org: string - Common string operations
  • python string concatenation with int site:stackoverflow.com

Issue concatenating 'str' and 'int' objects

You are converting your values to strings too soon, assuming you want to be able to print CPUcalc, GPUcalc and avgcalc later on. You are trying to make a calculation with GPUcalc and CPUcalc but those values are strings, when they really don't need to be.

Only convert values to strings when they have to be strings:

CPUcalc = date - CPU
GPUcalc = date - GPU
avgcalc = (GPUcalc + CPUcalc + buyyear) / 3

You also have a typo, you reference both avgcalc and avg_calc. Presumably only avgcalc exists:

if date > avgcalc:
print ("Your computer is " + str(avgcalc) + " years old. You might not need to upgrade your laptop/desktop, but if you think your laptop/desktop is slow, you may need to upgrade.")

elif date < avgcalc:
print ("Your computer is " + str(avgcalc) + " years old. You may need to upgrade your laptop/desktop, but if you think your laptop/desktop is not slow, you my not need to upgrade.")

else:
print "ERROR: The program didn't meet the requirements for the program to calculate if you need to upgrade or not."
print "The equation is: ((current year - CPU year) + (current year - GPU year) + bought year) divide by 3) = x"
print "If 'x' is less than 4, you may not need to upgrade"
print "If 'x' is more than 4, you may need to upgrade"

Note that you don't need to use str() to convert values to strings, that's only needed when concatenating non-string objects with strings. You can have print convert values to strings for you if you pass them to the statement separately (at which point print inserts spaces between each element):

if date > avgcalc:
print "Your computer is", avgcalc, "years old. You might not need to upgrade your laptop/desktop, but if you think your laptop/desktop is slow, you may need to upgrade."

elif date < avgcalc:
print "Your computer is", avgcalc, "years old. You may need to upgrade your laptop/desktop, but if you think your laptop/desktop is not slow, you my not need to upgrade."

else:
# ...

You can also use string formatting, with the str.format() method:

if date > avgcalc:
print "Your computer is {} years old. You might not need to upgrade your laptop/desktop, but if you think your laptop/desktop is slow, you may need to upgrade.".format(avgcalc)

elif date < avgcalc:
print "Your computer is {} years old. You may need to upgrade your laptop/desktop, but if you think your laptop/desktop is not slow, you my not need to upgrade.".format(avgcalc)

else:
# ...

The {} placeholder will convert values to a suitable string, or you can further configure how the value should be treated.

Note that your actual tests (date > avgcalc, date < avgcalc) and the text you print in the else branch don't agree with one another, where you say you test the calculation against the number 4.

Your calculation also doesn't make all that much sense, why would you add the year the computer was bought to the number of years that have passed since the CPU and GPU have been bought? You probably want to use (date - buyyear) in the avgcalc value. I'd also use the term age in each variable, to make it clearer what the values mean:

CPU_age = date - CPU
GPU_age = date - GPU
computer_age = date - buyyear
avg_age = (CPU_age + GPU_age + computer_age) / 3

if avg_age > 4:
# computer is old
else:
# computer is still new enough

Your else: branch doesn't make all that much sense, as that'd only happen if date and avgcalc were to be exactly equal. You probably want to learn about validating user input and use the error message there.

You can also consider using Python to get the current year, computers usually know the date already. Python has the datetime module, where datetime.date.today() gets you today's date, and the resulting object has a year attribute:

import datetime

# ...

date = datetime.date.today().year

Last but not least: if you are learning Python, it is strongly recommended that you switch to Python 3. Python 2, the language you are using now, will reach end-of-life January 2020, a little over 8 months from today.

Python TypeError: cannot concatenate 'str' and 'int' objects when trying to print

You forgot to reassign the new values:

timeInSeconds = 1823
timeInMinutes = timeInSeconds / 60
timeInRest = timeInSeconds % 60

timeInMinutes = str(timeInMinutes)
timeInRest = str(timeInRest)

print("Your time in minutes and seconds is " + timeInMinutes + ":" + timeInRest)

Basically doing this :

str(timeInMinutes)

Does not mean your TimeInMinutes variable is now a string. You have to reassign it like so :

timeInMinutes = str(timeInMinutes)

I believe this is what you meant to do.


However, it could be useful to keep the int values for later. If that's the case, you could just create new variables like so :

timeInMinutesStr = str(timeInMinutes)
timeInRestStr = str(timeInRest)

print("Your time in minutes and seconds is " + timeInMinutesStr + ":" + timeInRestStr)

Or, you could just convert the values directly in the print, to avoid having to assign new variables that you might not use later :

print("Your time in minutes and seconds is " + str(timeInMinutes) + ":" + str(timeInRest))

TypeError: cannot concatenate 'str' and 'int' objects when trying to use printf-style formatting

% has a higher precedence than +, so s % y + z is parsed as (s % y) + z.

If s is a string, then s % x is a string, and (s % y) + z attempts to add a string (the result of s % y) and an integer (the value of z).

TypeError: cannot concatenate 'str' and 'int' objects 1

s = 'azcbobobegghakl'
count = 0
if(s.find("b")):
p = s.index('b')
while p+2 <= len(s):
if(s[p+1] == 'o' and s[p+2] == 'b'):
count = count+1
p = p+2
else:
p = p+1
print (count)

You have an error on incrementing p.

I would suggest using regexp for this though.



Related Topics



Leave a reply



Submit