Python has several built-in data types. Sometimes, when writing Python code, you might need to convert one data type to another. For example, concatenate a string and integer, first, you’ll need to convert the integer into a string.
This article explains how to convert a Python integer to a string.
Python str()
Function
In Python, we can convert integers and other data types to strings using the built-in str()
function.
The str()
function returns a string version of a given object. It takes the following forms:
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')
object
– Object to be converted to a string.
The function accepts three arguments, but usually, when converting an integer to a string, you’ll pass only one argument (object
) to the function.
Converting a Python Integer into String
To convert the integer 23 to a string version, simply pass the number into the str()
function:
str(23)
type(days)
'23'
<class 'str'>
The quotes around 23 indicate that the number is not an integer but is an object of string type. Also, the type()
function shows that the object is a string.
'
), double ("
), or triple quotes ("""
).Concatenating Strings and Integers
Let’s try to concatenate strings and integers using the +
operator and print the result:
number = 6
lang = "Python"
quote = "There are " + number + " relational operators in " + lang + "."
print(quote)
Python will throw a TypeError
exception error because it cannot concatenate strings and integers:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
To convert the integer to a string, pass the integer to the str()
function:
number = 6
lang = "Python"
quote = "There are " + str(number) + " relational operators in " + lang + "."
print(quote)
Now when you run the code, it will be executed successfully:
There are 6 relational operators in Python.
There are also other ways to concatenate strings and numbers.
The built-in string class provides a format()
method that formats a given string using an arbitrary set of positional and keyword arguments:
number = 6
lang = "Python"
quote = "There are {} relational operators in {}.".format(number, lang)
print(quote)
There are 6 relational operators in Python.
On Python 3.6 and later, you can use f-strings, which are literal strings prefixed with ‘f’ containing expressions inside braces:
number = 6
lang = "Python"
quote = f"There are {number} relational operators in {lang}."
print(quote)
There are 6 relational operators in Python.
Lastly, you can use the old %-formatting:
number = 6
lang = "Python"
quote = "There are %s relational operators in %s." % (number, lang)
print(quote)
There are 6 relational operators in Python.
Conclusion
In Python, you can convert an integer to a string using the str()
function.
If you have any questions or feedback, feel free to leave a comment.