🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeConvert String to Int in Python

A Python program may receive digits as text but need a numeric value for whole-number arithmetic. The built-in int() parses integer text into an integer, while str() turns a number into text again.
I’ll show how int() converts integer text, then how to convert a number back to text with str().
TL;DR: Use int() and str()
Call int(text) to parse a string containing an integer, then call str(number) when you need a string representation again.
- Use int(text) for decimal text such as “75846”.
- Pass a base for binary, octal or hexadecimal digits.
- Catch ValueError when input may not contain a valid integer.
- Keep identifiers as text when leading zeroes carry meaning.
What is string-to-integer conversion?
String-to-integer conversion means parsing digit text into an int value that Python can use in whole-number arithmetic. The accepted digits depend on the selected base, and invalid text raises ValueError.
For example, the characters “42” are text until int(“42”) produces the integer 42. The printed characters can look alike, so check type(value) when the distinction matters. Python’s built-in int() accepts an integer string and an optional base.
The conversion changes what the value means to your program. An integer can be added numerically, but it does not retain whether its original spelling used leading zeroes or a particular prefix. An account code such as “0042” should often remain a string even though its characters are digits.
| Input or operation | Result type | Use it when |
|---|---|---|
| “42” | str | Text must retain its spelling |
| int(“42”) | int | You need whole-number arithmetic |
| str(42) | str | You need text for output or joining |
For more on text values, see AskPython’s guide to Python strings. The int() documentation defines which text forms and bases Python accepts.
How to convert strings and integers step by step
Use int() to parse text, supply a base when the digits are not decimal, and use str() to turn a number back into text.
Step 1: Convert decimal text with int()
Pass a string containing decimal digits to int() when the text represents a whole number. The program below also prints the resulting type, parses a prefixed binary value and converts the first integer back to text.
decimal_text = "75846"
number = int(decimal_text)
print(f"{number} ({type(number).__name__})")
binary_text = "0b101101"
binary_number = int(binary_text, 0)
print(f"{binary_number} ({type(binary_number).__name__})")
output_text = str(number)
print(f"{output_text!r} ({type(output_text).__name__})")
Run the saved example with the command shown in the code example. Its output is:
75846 (int)
45 (int)
'75846' (str)

The binary prefix makes the second parse use base 2, producing 45. The final line is quoted and labeled str, while the converted numeric values are labeled int. I ran this command and got the output shown above.
Step 2: Convert a known base explicitly
The second argument to int() selects the radix, or base, of the digit sequence. Use base 2 for binary, 8 for octal and 16 for hexadecimal when the input contract gives you unprefixed digits in that format.
binary_value = int("101101", 2)
octal_value = int("100", 8)
hex_value = int("2a", 16)
print(binary_value, octal_value, hex_value)
These expressions produce 45, 64 and 42. The base is part of the interpretation: the text “100” means one hundred in base 10 but sixty-four in base 8. A base must be 0 or between 2 and 36, and digits beyond it raise ValueError.
Use base 0 only when Python-style prefixes such as 0b or 0x identify the format. It detects a prefix rather than guessing from arbitrary digits. Step 3 compares that behavior with an explicit base.
Step 3: Convert an integer to a string
Call str(number) when the integer must become text for a message, a text field or string concatenation. The result represents the numeric value in ordinary decimal notation.
count = 42
label = "Items: " + str(count)
print(label)
print(type(str(count)).__name__)
This prints Items: 42 and then str. An f-string can insert the integer directly for formatted output. The resulting value is still text.
Do not use str() to preserve an original spelling after parsing. Converting “0042” to an integer and back produces “42”, because an integer stores a value and not the source formatting.
Step 4: Compare automatic and explicit base selection
With base 0, int() recognizes valid prefixes such as 0x and 0b, and it rejects an unprefixed decimal string with a leading zero. An explicit base treats digits according to the base you supply.
for text in ("0x2a", "010", "0b1010"):
try:
print(f"{text!r} -> {int(text, 0)}")
except ValueError as error:
print(f"{text!r} -> {type(error).__name__}: {error}")
print(f"explicit base 10: {int('010', 10)}")
print(f"explicit base 8: {int('010', 8)}")
Run the command shown with the base-selection example to see the measured output:
'0x2a' -> 42
'010' -> ValueError: invalid literal for int() with base 0: '010'
'0b1010' -> 10
explicit base 10: 10
explicit base 8: 8

I ran the comparison and got a ValueError for “010” with base 0, while explicit base 10 returned 10 and base 8 returned 8. This result makes the choice practical: use base 0 for prefixed literals and a known base for unprefixed input.
Edge cases when converting strings and integers
int() accepts integer-form text, not every string that looks numeric. Invalid input raises ValueError. Validate according to the expected input format, and preserve text when spelling carries meaning.
| Input | Behavior | What to do |
|---|---|---|
| ” -12 “ | Whitespace and sign are accepted | Parse with int(text) |
| “3.14” | ValueError from int() | Use float() if a fractional value is intended |
| “42px” | ValueError | Decide whether units should be parsed separately |
| “0042” | Converts to integer 42 | Keep the original as text for codes or fixed-width values |
| “” | ValueError | Handle missing input before parsing |
Leading and trailing whitespace, an optional leading sign and underscores between digits are accepted by int() in current Python. A decimal point is different: int(“3.14”) does not round or truncate a string. For a numeric float value, int(3.14) truncates toward zero, so choose float() first only when that behavior fits the task.
Handle invalid text with try and except
Catch ValueError around conversion when text comes from a user or external source. This runnable example prints the specific failure from the decimal-point input.
try:
int("3.14")
except ValueError as error:
print(f"{type(error).__name__}: {error}")
Run it as the command shown in the example. Python prints:
ValueError: invalid literal for int() with base 10: '3.14'

I ran this input and got the ValueError shown above. The string has the right type for int(), but its decimal point makes it invalid as an integer literal. AskPython’s guide to handling ValueError covers broader exception choices.
A check such as str.isdigit() can reject some inputs before conversion, but it does not accept a leading minus sign and should not be treated as a replacement for parsing. For general signed values, try int() and handle ValueError, or validate against the exact format your program expects.
When converting multiple values, a list comprehension applies int() to each item, but one invalid item raises ValueError and stops the expression. If inputs can be mixed, process each value inside a try block so you can report or skip only the invalid entries. For a Pandas column, use the library’s column-conversion methods instead of treating the whole column as one scalar string.
When the input is collected with input(), Python gives your program a string even when a person types digits. Convert only after deciding what the field represents. Keep postal codes, ticket numbers and account identifiers as strings when they function as labels.
Whitespace is common when text comes from a copied field or a line in a file. int() accepts surrounding whitespace, so ” -12 ” parses as negative twelve. Validate separately if your input rules forbid spaces or require the sign to touch the digits.
Base selection matters when data comes from a protocol, a bit mask or a file format. The string “101” in base 2 is five, but in base 10 it is one hundred and one. Pass 2 for unprefixed binary, or base 0 when the input uses a recognized prefix.
For bases above ten, letters represent digit values after nine. In hexadecimal, A or a means ten and F or f means fifteen. The string “2a” parses with base 16 but fails under default base 10.
Numeric-looking text can still use a format int() does not accept. The text “1,000” is not parsed with a thousands separator, and “3.14” contains a decimal point. Establish the input convention, then reject or normalize only forms it permits.
If a decimal value is intended, float(text) parses forms such as “3.14”. Converting that float to int then discards the fractional part toward zero. That is different from rounding to the nearest whole number, so financial amounts or measurements need a deliberate rounding policy rather than an incidental call to int().
For collections, a list comprehension is concise when every element is guaranteed valid. With uncertain data, convert items one at a time inside a try block and decide how to handle each failure. When every item must be valid, raise the error and stop so the caller cannot mistake a partial list for a complete result.
Converting back with str() is useful for composing a message or preparing a text field, but it does not recreate the exact input. It cannot tell whether the original text used a plus sign, leading zeroes, uppercase hexadecimal letters or whitespace. Keep the source string alongside the parsed integer when both the machine-readable value and the original spelling matter.
Conclusion
Use int() when text follows an integer format, and use str() when a number must become text. Choose a base from the data contract, handle ValueError for uncertain input and retain the original string when formatting matters.
FAQ
These answers cover common questions about converting between text and integers.
How do you convert a string to an integer in Python?
Call int(text), such as int(“42”). The text must use a valid integer format or Python raises ValueError.
How do you convert an integer to a string in Python?
Call str(number), such as str(42), or insert the integer in an f-string when building formatted text.
Why does int(“3.14”) raise ValueError?
The string contains a decimal point and represents a fractional value, not an integer literal. Use float() if fractional arithmetic is intended, then choose an explicit rounding or truncation rule.
How do you convert a binary string to an integer?
Pass base 2 for unprefixed binary digits, as in int(“1010”, 2). For a prefixed value such as “0b1010”, int(text, 0) recognizes the prefix.


