The simplest way to convert a string to an integer
Use the int() function with your string as the argument. If your string contains only digits, possibly with a leading minus sign, this converts it to an integer in one line.
Here is the most basic example:
number = int("42")
After this line runs, number holds the integer 42, not the string "42". You can now use it in math, comparisons, or anywhere else that requires an actual number rather than text.
The int() function also accepts a second argument called the base, which tells Python what number system the string uses. The default is base 10 (decimal). If you need to convert from binary, hexadecimal, or another base, you specify it as the second argument — but for most everyday work, you only need int() with one argument.
Key Takeaways
- The int() function converts a string of digits into an integer: int("123") becomes 123.
- If the string contains non-digit characters (except a leading minus sign), int() will crash with a ValueError unless you handle the error.
- Wrap int() in a try-except block to catch errors when you are not sure the string contains only digits.
- Use the second argument to int() if your string is in a base other than decimal, such as int("1010", 2) for binary.
- Check whether your string is empty or contains only whitespace before converting, because int() will reject both.
Handling strings that contain letters or special characters
If you try to convert a string that contains anything other than digits (and an optional leading minus sign), int() stops and raises a ValueError. The program crashes unless you catch the error.
For example, int("42 apples") fails because of the space and the word. int("3.14") fails because of the decimal point, even though 3.14 looks like a number to a human.
The safest approach is to wrap the conversion in a try-except block. This tells Python what to do if the conversion fails:
try: number = int(user_input) except ValueError: print("That is not a valid integer") number = 0
Now if the user types something that is not a valid integer, the program prints a message and sets number to 0 instead of crashing. You can replace the message and the fallback value with whatever makes sense for your program.
Removing whitespace before converting
Strings often arrive with extra spaces at the beginning or end, especially when you read them from user input or from a file. The int() function rejects strings with leading or trailing whitespace.
Use the strip() method to remove whitespace before converting:
number = int(user_input.strip())
The strip() method removes spaces, tabs, and newline characters from both ends of the string. It does not change the original string — it returns a new string without the whitespace. Then int() converts that cleaned string to an integer.
This is especially useful when reading from files or when users paste text that includes accidental spaces. Combining strip() and int() handles the most common real-world case where a string looks like a number but has invisible whitespace around it.
Converting strings in different number bases
By default, int() assumes your string is in base 10 (decimal). If your string represents a number in a different base, pass that base as the second argument.
Here are the most common bases you will encounter:
- int("1010", 2) converts the binary string "1010" to 10 in decimal.
- int("FF", 16) converts the hexadecimal string "FF" to 255 in decimal.
- int("77", 8) converts the octal string "77" to 63 in decimal.
The base argument can be any number from 2 to 36. In bases higher than 10, letters represent digits — A is 10, B is 11, and so on. The int() function accepts both uppercase and lowercase letters, so int("ff", 16) and int("FF", 16) both work.
If you pass a base but the string contains a digit that does not exist in that base, int() raises a ValueError. For example, int("9", 8) fails because 9 does not exist in octal (base 8 only uses digits 0 through 7).
Converting floats that are stored as strings
If your string contains a decimal point, int() will reject it. You have two choices: convert to a float first, then to an integer, or strip the decimal part before converting.
To convert a decimal string to an integer, first convert it to a float, then to an integer:
number = int(float("3.14"))
This converts "3.14" to the float 3.14, then to the integer 3. The int() function always rounds toward zero, so 3.14 becomes 3 and -3.14 becomes -3. It does not round to the nearest integer — it truncates.
If you want to round to the nearest integer instead, use the round() function after converting to float:
number = round(float("3.14"))
This gives you 3. If the string were "3.6", round() would give you 4. Choose the method that matches what your program needs to do with the number.
Checking if a string can be converted before attempting it
Sometimes you want to know whether a string is convertible before you actually convert it. The isdigit() method returns True if the string contains only digits, and False otherwise.
if user_input.isdigit(): number = int(user_input) else: print("Please enter digits only")
Be aware that isdigit() returns False for strings with a leading minus sign, even though int() can convert them. If you need to accept negative numbers, use a try-except block instead of isdigit().
Another option is the isnumeric() method, which is similar to isdigit() but also accepts some Unicode characters that represent numbers. For most programs, isdigit() is sufficient and clearer about what it does.
Common mistakes and how to fix them
The most frequent error is forgetting that int() rejects strings with decimal points. If you have "3.14" and you try int("3.14"), it crashes. Convert to float first: int(float("3.14")).
Another common mistake is not stripping whitespace. A string that looks like "42" but actually contains leading spaces will fail. Always use strip() when the string comes from user input or a file: int(user_input.strip()).
A third mistake is assuming int() rounds. It does not — it truncates toward zero. If you need rounding, use round(float(string)) instead.
Finally, forgetting to handle the ValueError is a mistake that crashes programs in production. Always wrap int() in a try-except block when you are not 100% certain the string contains only digits, or use isdigit() to check first.
Frequently Asked Questions
What happens if I try to convert an empty string?
int("") raises a ValueError. If your program might receive empty strings, check for them before converting or wrap the conversion in a try-except block. You can check with if user_input.strip(): to see if the string has any non-whitespace characters.
Can I convert a string with commas, like "1,000"?
Not directly — int("1,000") fails because of the comma. Remove the comma first: int("1,000".replace(",", "")). The replace() method removes all commas, then int() converts the result.
Why does int("007") give 7 instead of keeping the leading zeros?
Integers do not have leading zeros — they are just numbers. The leading zeros were only meaningful when the value was stored as a string. Once you convert to an integer, the zeros are gone. If you need to preserve leading zeros, keep the value as a string.
What is the difference between int() and float()?
int() converts to an integer (a whole number with no decimal point), while float() converts to a floating-point number (which can have a decimal point). Use int() when you need whole numbers only, and float() when you need decimals. You can convert between them: int(float("3.14")) or float(int("42")).
Can I convert a string to an integer in a different base and then change the base again?
Once you convert a string to an integer using int(), the base information is lost — the integer is just a number. If you convert it back to a string, it will be in base 10 by default. To display an integer in a different base, use functions like bin(), hex(), or oct(), or use format strings like format(42, 'b') for binary.