Converting a string to an integer is a common task in Python, especially when you read numbers from user input, files, or APIs. This guide shows you how to safely turn a numeric string like "42" into the integer 42 using the built-in int() function, and how to handle strings that aren’t clean numbers.
What You’ll Need
- Python 3 installed on your computer (any recent version works).
- A text editor or IDE (like VS Code, PyCharm, or even Notepad).
- Basic familiarity with running Python scripts or using the interactive shell.
Step-by-Step
- Open a Python environment. You can use the interactive shell by typing
pythonin your terminal, or create a new.pyfile in your editor. - Start with a simple string. For example, assign a numeric string to a variable:
s = "123". - Call the
int()function. Pass the string as an argument:n = int(s). The variablennow holds the integer123. - Verify the type. Use
print(type(n))to confirm it’s<class 'int'>. This is a good habit when you’re debugging. - Handle negative numbers. The
int()function understands the minus sign:int("-45")returns-45. - Handle leading/trailing whitespace. Python automatically strips spaces, so
int(" 7 ")works and returns7. You don’t need to call.strip()first, but doing so is harmless. - Deal with decimal strings carefully. If the string is
"3.14",int()will raise an error. First convert tofloatand then toint:int(float("3.14"))gives3(truncates toward zero). - Use a base for non-decimal strings. If you have a binary or hex string, pass the base as the second argument. For example,
int("1010", 2)returns10, andint("ff", 16)returns255. - Wrap in a try-except for safety. When the string might not be a number, catch the
ValueError:
try:
n = int(s)
except ValueError:
print("That's not a valid integer.")
Common Mistakes
- Passing a float string directly.
int("3.14")raises aValueErrorbecause the string contains a decimal point. You must convert tofloatfirst. - Forgetting that
int()truncates, not rounds.int(3.99)gives3, not4. If you need rounding, useround()before converting. - Ignoring non-numeric characters. Strings like
"12abc"or"1,000"will cause errors. Remove commas or other symbols before conversion. - Using
int()onNoneor empty strings. Both raise errors. Check forNoneand empty strings in your logic. - Assuming the string is in base 10. If you have a hex string like
"0x1A",int()without a base will fail. Useint("0x1A", 16)orint("1A", 16).
Tips
- Use
isdigit()for quick checks. The string methods.isdigit()returnsTrueif all characters are digits (and the string is not empty). It’s a handy pre-check, but note it returnsFalsefor negative numbers or decimals. - Use
map()for lists. If you have a list of strings like["1", "2", "3"], you can convert them all at once:list(map(int, strings))or[int(x) for x in strings]. - Be aware of locale-specific formats. Some countries use commas as decimal separators (e.g.,
"3,14"). Replace the comma with a dot before converting:float(s.replace(',', '.')). - Use
int()with a default fallback. In Python 3.11+, you can useint(s, default=0)to return a default value instead of raising an error. For older versions, use a try-except. - Remember that
int()also works on bytes. If you read from a binary file,int(b'42')works, but be careful with encoding.
Troubleshooting
I get a ValueError: invalid literal for int()
The string contains characters that aren’t digits, a sign, or whitespace. Check for hidden spaces, commas, or letters. Use repr(s) to see exactly what the string contains.
I get a TypeError: int() argument must be a string or a number
You’re passing something that isn’t a string or number, like a list or a None. Verify the variable type with type(s).
The conversion works but gives a wrong number.
Check if the string has leading zeros (like "007") – int() handles them fine, but if you’re doing something else, you might need to strip them. Also, check if you accidentally used a float conversion that rounds.
I’m reading from a file and it fails.
File lines often end with a newline character \n. Use s.strip() before converting, or use int(s) – Python strips whitespace anyway, but if the line has other invisible characters, strip them.
I need to convert a string like “1,234” with a comma.
Remove the commas first: int(s.replace(',', '')). This works for thousands separators.
Frequently Asked Questions
Q: Can I convert a string with a plus sign?
A: Yes, int("+5") returns 5. The plus sign is allowed.
Q: What happens if the string is empty?
A: int("") raises a ValueError. You should check for empty strings before converting.
Q: How do I convert a string to a float?
A: Use float(s). For example, float("3.14") returns 3.14.
Q: Is there a difference between int("10") and int("10", 10)?
A: No, the default base is 10, so both return 10. The second argument is only needed for other bases.
Q: Can I convert a string that represents a very large number?
A: Yes, Python’s integers have arbitrary precision, so int("12345678901234567890") works fine.
Q: How do I handle a string that might be a float or an int?
A: Try int(s) first, and if it fails, try float(s). Or use float(s) and then convert to int if needed, but be aware of truncation.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Fix Windows 10 Wi-Fi Not Connecting: Step-by-Step
- Scaling Headless Chrome: A Practical Guide
- Fix Windows Upgrade Error 0x80090011
- Fix Microsoft Store Apps Not Updating
- v0 Alternatives: Which Fits Your Web App Build?9.26 yd³
- Fix Hard Disk Error 0x80071ac3