Python, can I concatenate a string and an int?

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
john8217Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gelonidaCommented:
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

peprCommented:
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.)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gelonidaCommented:
@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

OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

john8217Author 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 ExpertCommented:
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()
gelonidaCommented:
@Sudobh: see line 10 of my first answer
Subodh Tiwari (Neeraj)Excel & VBA ExpertCommented:
Yes, now I see that you already showed that example. Sorry I didn't see it.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.