• Register
1 vote
31 views

Problem:

I am quite new in python programming. I have written a simple python that I can’t run. For an unknown reason, it throws me back an error “cannot concatenate 'str' and 'int' objects

Here is my sample snippet:

n = raw_input("Enter n: ")
m = raw_input("Enter m: ")
print "n + m as strings: " + n + m
n = int(n)
m = int(m)
c = m + n
str(c)
print "n + m as integers: " + c

Any solution?

12 7 7
15,250 points

2 Answers

1 vote

Solution:

You have two ways to solve it, 

Either

c = str(c) 

Or

You can put a comma (,) in front of the variable c in your print line

n = raw_input("Enter n: ")
m = raw_input("Enter m: ")
print "n + m as strings: " + n + m
n = int(n)
m = int(m)
c = m + n
str(c)
print "n + m as integers: ", c

This program will produce the output:

Enter n: 3
Enter m: 7
n + m as strings:  37
n + m as integers:  10

Thanks

13 9 6
94,240 points
0 votes

Solution:

There are two methods to solve the problem which is caused by the last print statement.

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

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

in which instance

str(c)

isn't required 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

Therefore, str(c) returns a new string representation of c, and does not mutate c itself.

c = str(c) 

In case you need to close int or floats to a string you should use this:

i = 123
a = "foobar"
s = a + str(i)
c = a + b 
str(c)

Really, in this last line you are not altering the type of the variable c. In case you do

c_str=str(c)
print "a + b as integers: " + c_str

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

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

.. and for sequence types, it imply "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 alter objects from one type to another1 in order to create operations "make sense", since that would be confusing: for example, you might conceive that '3' + 5 must mean '35', however someone else might think it must mean 8 or even '8'.

Likewise, 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

Since of this, you require to do the conversion apparently, whether what you want is concatenation or addition:

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

But, there is a better method. Relying on which version of Python you exercise, there are three different kinds of string formatting available2, which not only approve 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.'

However also approve 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).'

If you employ % interpolation, str.format(), or f-strings is up to you: % interpolation has been around the longest , str.format() is mostly more powerful, and f-strings are more powerful still (however available only in Python 3.6 and later).

Another alternative is to exercise the fact that in case you give print multiple positional arguments, it will link their string illustrations together employing 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.

Employ the str function in order to convert "currency" to a string

def shop():
      print "Hello " + name + ", what would you like? You have $" + str(currency)

Your value in row[0] is an integer, however you are attempting to combine (concatenate) it with a string (text). You can solve this by Mortally casting row[0] as a string employing the built in str() method.

Attempt this:

arcpy.MakeFeatureLayer_mangement(Fitting, "fcLyr", "OBJECTID = "+ str(row[0]))

Or you could use the format method to insert the integer directly into the query string:

arcpy.MakeFeatureLayer_management(Fitting, "fcLyr", "OBJECTID = {}".format(row[0]))

 

10 6 4
31,120 points

Related questions

1 vote
1 answer 15 views
15 views
Problem: I am a new student in Python programming. I have made a program that is supposed to take multiple inputs from the user and then print simply. Yeah, I know that sounds pretty easy but I am facing some kind of TypeError from the program. I am attaching the ... am getting is: TypeError: can only concatenate str (not "int") to str What&rsquo;s wrong here? Thanks for your kind help, mate.
asked Jun 29 adamSw 11.3k points
1 vote
2 answers 87 views
87 views
Problem : The program supposed to take in two names, and if they are the same length it should check if they are the same word. But i am getting below error in python python typeerror: not all arguments converted during string formatting
asked Oct 21, 2019 peterlaw 6.9k points