How can I concatenate str and int objects?

+1 vote

How To Concetanate Strings and Integers in Python?
I am trying to execute the following code:
things = 5
print("You have " + things + " things.")
I get the following error in Python 3.x:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int

Apr 15, 2018 in Python by ana1504.k
• 7,870 points
54 views

4 answers to this question.

+1 vote

'+' operator can be used to either add two numeric values or to concatenate sequences.
For example:
A = 1
B = 2
Print (A + B)
Output = 3

Print ([1,2,3,’name’] + [1,2,5, ’name’])
Print (‘string-1’ + ‘string-2’)
Output = [1,2,3,’name’,1,2,5,’name’]
Output = string-1string-2

answered Apr 15, 2018 by anto.trigg4
• 3,420 points
+1 vote
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> 'abc' + 'def'
'abcdef'
answered Oct 18, 2018 by ritu
+1 vote
  1. either: print("You have " + str(things) + " things.") (the old school way)

  2. or: print("You have {} things.".format(things)) (the new pythonic and recommended way)

answered Oct 18, 2018 by ruvi
+1 vote

If you want to concatenate int or floats to a string you must use this:

i = 123
a = "foobar"
s = a + str(i)
answered Oct 18, 2018 by subhm

Related Questions In Python

0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
97 views
0 votes
1 answer

How can I print variable and string on same line in Python?

Use , to separate strings and variables while printing: print ...READ MORE

answered Sep 17, 2018 in Python by Priyaj
• 56,920 points
76 views
0 votes
1 answer

How can i combine flask and nameko?

You absolutely can use nameko and Flask together.  In that ...READ MORE

answered Feb 4 in Python by SDeb
• 13,180 points
213 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 346 views
+4 votes
6 answers
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
121 views
+2 votes
6 answers

How can I change directory or "cd" in Python?

Context Manager: cd import os class cd:     """Context manager for ...READ MORE

answered Oct 18, 2018 in Python by Nabarupa
136 views