Convert integer to string in Python
To convert an integer to a string in Python, use the str()
function. For example:
This will output the string "42"
.
You can also use the format()
function to convert an integer to a string, like this:
This will also output the string "42"
.
If you want to convert an integer to a string with a specific base (such as binary or hexadecimal), you can use the format()
function like this:
num = 42
# Convert to binary
num_str = "{:b}".format(num)
print(num_str)
# Convert to hexadecimal
num_str = "{:x}".format(num)
print(num_str)
This will output the strings "101010"
and "2a"
, respectively.