Use the built-in str() function (str(number)) to convert an integer into a string in Python. It works for positive integers, negative integers, zero, and arbitrarily large numbers in $O(n)$ time (where $n$ is the number of digits).
Basic Example
# 1. Define integer variables
count = 42
temperature = -7
# 2. Convert integers to strings using str()
count_str = str(count)
temp_str = str(temperature)
print(count_str) # Output: "42"
print(type(count_str)) # Output: <class 'str'>
print("Count: " + count_str) # Output: "Count: 42"
Key Details & Alternative Methods
- Concatenation requires explicit conversion: Unlike JavaScript or Java, Python does not implicitly convert integers when using
+with strings ("Age: " + 25raises aTypeError). Wrap the integer instr()or use an f-string instead. - String interpolation (
f-strings): If you are embedding an integer directly inside a larger text template, using an f-string (f"{count}") is cleaner and faster than callingstr()separately:score = 95 message = f"Your final score is {score}%" - Formatting numbers (thousands separators, padding, bases): When you need custom string formatting—such as leading zeros, comma separators, or hexadecimal/binary representations—use
format()or f-string format specifiers:num = 42 large_num = 1500000 print(f"{num:05d}") # Output: "00042" (zero-padded to 5 digits) print(f"{large_num:,}") # Output: "1,500,000" (comma-separated) print(hex(num)) # Output: "0x2a" (hexadecimal string) print(bin(num)) # Output: "0b101010" (binary string) - Converting a list of integers to strings: Use
map(str, numbers)or a list comprehension ([str(x) for x in numbers]), which is especially useful before calling"".join(...).
Comparison of Integer-to-String Methods
| Method | Syntax | Output (num = 42) |
Best Used When |
|---|---|---|---|
str(num) |
str(42) |
"42" |
Direct type conversion of a single integer. |
| f-string | f"{num}" |
"42" |
Embedding numbers into sentences or applying format specifiers. |
format() |
format(42, "04d") |
"0042" |
Applying dynamic padding, alignment, or thousands separators. |
hex() / bin() / oct() |
bin(42) |
"0b101010" |
Converting integers into non-decimal base strings. |
You must log in or register to comment.
