sodcalculator

10 Tech How-To

Convert String to Int in Python: Step-by-Step

Guide 10-38315 · Updated · Step by step

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

  1. Open a Python environment. You can use the interactive shell by typing python in your terminal, or create a new .py file in your editor.
  2. Start with a simple string. For example, assign a numeric string to a variable: s = "123".
  3. Call the int() function. Pass the string as an argument: n = int(s). The variable n now holds the integer 123.
  4. Verify the type. Use print(type(n)) to confirm it’s <class 'int'>. This is a good habit when you’re debugging.
  5. Handle negative numbers. The int() function understands the minus sign: int("-45") returns -45.
  6. Handle leading/trailing whitespace. Python automatically strips spaces, so int(" 7 ") works and returns 7. You don’t need to call .strip() first, but doing so is harmless.
  7. Deal with decimal strings carefully. If the string is "3.14", int() will raise an error. First convert to float and then to int: int(float("3.14")) gives 3 (truncates toward zero).
  8. 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) returns 10, and int("ff", 16) returns 255.
  9. 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 a ValueError because the string contains a decimal point. You must convert to float first.
  • Forgetting that int() truncates, not rounds. int(3.99) gives 3, not 4. If you need rounding, use round() before converting.
  • Ignoring non-numeric characters. Strings like "12abc" or "1,000" will cause errors. Remove commas or other symbols before conversion.
  • Using int() on None or empty strings. Both raise errors. Check for None and 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. Use int("0x1A", 16) or int("1A", 16).

Tips

  • Use isdigit() for quick checks. The string method s.isdigit() returns True if all characters are digits (and the string is not empty). It’s a handy pre-check, but note it returns False for 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 use int(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

The whole Tech How-To bed →