Categories
Python Answers

How to concatenate str and int objects with Python?

Spread the love

Sometimes, we want to concatenate str and int objects with Python.

In this article, we’ll look at how to concatenate str and int objects with Python.

How to concatenate str and int objects with Python?

To concatenate str and int objects with Python, we can use the string’s format method, string interpolation or an f-string.

For instance, we write:

things = 3
s1 = 'You have %d things.' % things
s2 = 'You have {} things.'.format(things)
s3 = f'You have {things} things.'
print(s1)
print(s2)
print(s3)

We use string interpolate to create s1.

%d is a placeholder for a number within the string.

Then we put the variables we interpolate after the % sign.

To create s2, we put curly braces in the string for the placeholder.

Then we call format on the string with the variables we want to interpolate.

Finally, we create s3 with the f prefix and the variable right inside the string surrounded by curly braces.

f-strings are available since Python 3.6.

Therefore, s1, s2, and s3 are all 'You have 3 things.'.

Conclusion

To concatenate str and int objects with Python, we can use the string’s format method, string interpolation or an f-string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *