• Register
1 vote
34 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

Please log in or register to answer this question.

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

0 votes
1 answer 18 views
18 views
Problem: I have this python program that adds strings to integers: a = raw_input("Enter a: ") b = raw_input("Enter b: ") print "a + b as strings: " + a + b a = int(a) b = int(b) c = a + b str(c) print "a + b as integers: " + c I get this error: Python: TypeError: cannot concatenate 'str' and 'int' objects How can I add strings to integers?
asked Jan 7 Mashhoodch 5.7k points
1 vote
1 answer 60 views
60 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, 2020 adamSw 11.3k points
0 votes
1 answer 61 views
0 votes
1 answer 89 views
0 votes
1 answer 28 views
28 views
Problem: Hello! I am a beginner. I just moved from Java to Python programming just recently. I am learning the syntax of Python. I am trying to print the multiplication table using the while loop. I have written the following program in an attempt to do that: number ... to str implicitly I do not have any clue regarding this error. Can anybody here help me solving this error? I would be thankful.
asked Jan 8 Code Learner 5.5k points
0 votes
1 answer 52 views
1 vote
2 answers 100 views
100 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
0 votes
1 answer 2 views
2 views
Problem: I've very recently migrated to Py 3.5. This code was working properly in Python 2.7: with open(fname, 'rb') as f: lines = [x.strip() for x in f.readlines()] for line in lines: tmp = line.strip().lower() if 'some-pattern' in tmp: continue # ... code After upgrading to 3.5, I'm getting the: TypeError: a bytes-like object is required, not 'str'
asked 16 hours ago Mashhoodch 5.7k points
1 vote
1 answer 304 views
304 views
Problem: I wrote a program in which gives me the following error : TypeError: startswith first arg must be bytes or a tuple of bytes, not str The program I wrote is: def allFasta(filename): xd = open(filename, 'yb') headers = "" sequence = "" while True: ... ("youn.xd") Why is this type error message is appearing for this program. Is there any problem with my programs arguments? Thanks in advance.
asked Jun 11, 2020 samhaz 5k points
0 votes
1 answer 9 views
9 views
Problem: Hi there! I just recently learned loops in Python that are a bit complex and tricky. I got an assignment from my teacher in which I have to write a program that takes a number as input from the user and prints the multiplication table of that number. I tried ... that the user does not enter a negative number. I do not know what the problem is and how to resolve it. Any help? Thanks.
asked Dec 2, 2020 Code Learner 5.5k points