Concatenate a String and Integer in Python

Concatenate a String and Integer in Python

String manipulation is a common task in many languages, especially when creating user interfaces. One of the most common tasks is to concatenate a string and an integer together. Here we'll show you a few different ways to achieve this in Python.

Adding a String and an Integer

Using the + operator, we can add a string and an integer together. However, you must first convert the integer to a string since Python won't do it for you.

>>> the_str = "My daughter's age is: "
>>> age = 3
>>> the_str + str(age)
"My daughter's age is: 3"

If you don't convert the integer to a string, you'll get an error similar to this:

>>> the_str = "My daughter's age is: "
>>> age = 3
>>> the_str + age
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

f-Strings

Another option that works well for formatting strings is Python 3's "f-string". This is a new feature in Python 3.6 and allows you to format strings in a more readable way.

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

>>> the_str = "My daughter's age is:"
>>> age = 3
>>> f'{the_str} {age}'
"My daughter's age is: 3"

While this isn't necessarily a shorter way to achieve the same thing (it takes 18 characters vs 17 with the + operator), it is a much more readable way to format strings.

One thing that's nice about doing it this way is that some of the formatting can be done in the f-string and not in the string variable. Notice that the_str doesn't have a space at the end, which is now in between the variables in the f-string.

Format

Finally, there is a third option for formatting strings. You can use the format function to format strings, which uses placeholders within strings.

>>> the_str = "My daughter's age is:"
>>> age = 3
>>> '{} {}'.format(the_str, age)
"My daughter's age is: 3"

This is slightly similar to f-strings, but it is a little more verbose and available in Python 2.x. And again, it has the advantage of allowing more formatting to be put in the placeholder string and not the variables.

Last Updated: July 2nd, 2022
Was this helpful?
Project

Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
David Landup
Details
Project

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic
Details

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms