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

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

Ā© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms