Python, can I concatenate a string and an int?

john8217
john8217 used Ask the Experts™
on
I started learning Python. I created this simple code which involves concatenating a string and an integer. I just found out that Python doesn't like that. Here is the code I'm typing. Python gave me an error message because of line 4.
     character_name = "John"
     character_age = 35
     print("There was a man named " + character_name + ".")
     print("He was " + character_age + " years old")
     character_name = "Mike"
     print("There was someone else named " + character_name + ".")
     print("But he didn't like being 35")
How do I concatenate a string an in int
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You cannot concatenate a string and an integer.

Howver you can convert the integer to a string to concatenate or you can use string formatting.

There's two different kinds of string formatting.
The 'old style formatting', that's more similiar to the printf formatting style of the C language
and the new formatting style which is more powerful, but a little more to type for simple cases.

Old style with the '%' operator

New style formatting with the .format() method

Documentation for new style formatting:
https://docs.python.org/3/library/string.html?highlight=string#string.ascii_uppercase
and examples at
https://docs.python.org/3/library/string.html?highlight=string#formatexamples

Documentation for old style formatting:
https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

      character_name = "John"
     character_age = 35
     print("There was a man named " + character_name + ".")
     print("There was a man named %s." % character_name)
      print("There was a man named {}.".format(character_name))
     print("He was " + str(character_age) + " years old")
     print("He was %d years old" % character_age)
     print("He was {} years old".format(character_age))
     print("The man %s was %d years old" % (character_name, character_age))
     print("The man {} was {} years old".format(character_name, character_age))
     character_name = "Mike"
     print("There was someone else named " + character_name + ".")
     print("But he didn't like being 35")

Open in new window

To add to Gelonida's answer, you can use also the format_map() method of the string (since Python 3.2), where the curly braces can contain the name of the key to the dictionary.
>>> character_name = 'John'
>>> character_age = 35
>>> 'The man {name} was {age} years old'.format_map({'name': character_name, 'age': character_age})
'The man John was 35 years old'

Open in new window


This is nice if you already have the dictionary filled for other purposes. (The above is a bit clumsy.)

However, since Python 3.6, there is new and nice feature called formatted string literals. You simply add the f prefix before the literal, and then you just put the name of the variable inside the curly braces:

>>> character_name = 'John'
>>> character_age = 35
>>> f'The man {character_name} was {character_age} years old'
'The man John was 35 years old'

Open in new window


Actually, you can write the expression inside:
>>> f'The man {character_name.upper()} was {character_age + 10} years old'
'The man JOHN was 45 years old'

Open in new window


(The feature is known also in other programming languages.)
@pepr: True.
the new formatted string literal is the third way of formatting which I forgot to mention

even the old style % operator supports map formatting.
So if you have a dict instead of separate viarables, then it's also possible to do.

info = { "name":  "John", "age": 35}

# old style
print("The name is %(name)s and the age is %(age)d" % info)

# new style
print("The name is {name} and the age is {age}".format_map(info))

Open in new window

Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

Author

Commented:
Thank you both.
Geez, I didn't know that something so seemingly simple as concatenation could be so involved.
Subodh Tiwari (Neeraj)Excel & VBA Expert
Most Valuable Expert 2018
Awarded 2015

Commented:
Also it can be written in short like this...
>>> character_name = 'john'
>>> character_age = 35
>>> 'The man {} was {} years old'.format(character_name,character_age)
'The man john was 35 years old'

Open in new window

Each {} in the string is a placeholder which can be replaced with it's corresponding variable within .format()
@Sudobh: see line 10 of my first answer
Subodh Tiwari (Neeraj)Excel & VBA Expert
Most Valuable Expert 2018
Awarded 2015

Commented:
Yes, now I see that you already showed that example. Sorry I didn't see it.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial