The simplest way to convert a string to an integer

Use the int() function with the string as its argument. If your string contains only digits, possibly with a leading minus sign, int() will convert it directly to a whole number.

For example, int("42") returns the integer 42. The string "42" and the integer 42 are different things in Python — one is text, the other is a number you can do math with. The int() function bridges that gap.

If your string has spaces at the beginning or end, int() ignores them automatically. int(" 42 ") works just as well as int("42").

Key Takeaways

  • The int() function converts a string of digits into an integer you can use for math and comparisons.
  • If the string contains non-digit characters (except a leading minus sign), int() will raise a ValueError and stop your program.
  • Use a try-except block to catch errors when you are not sure the string contains a valid number.
  • Specify a base as the second argument to int() if your string represents a number in a different system, like hexadecimal or binary.
  • The isdigit() method checks whether a string contains only digits before you attempt conversion.

What happens when the string is not a valid number

If your string contains letters, punctuation, or other characters that are not digits, int() raises a ValueError and your program stops at that line. For instance, int("42a") fails because "a" is not a digit.

To prevent your program from crashing, 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 number")

The code inside the try block runs first. If int() raises a ValueError, Python skips the rest of the try block and runs the code inside except instead. This way your program keeps running even if the conversion fails.

Checking if a string is safe to convert before you try

You can test whether a string contains only digits using the isdigit() method before you call int(). If isdigit() returns True, the string is safe to convert. If it returns False, the string contains at least one non-digit character.

"42".isdigit() returns True. "42a".isdigit() returns False. This method is useful when you want to decide what to do before attempting conversion, rather than handling an error after the fact.

One limitation: isdigit() returns False for strings with a leading minus sign, even though int("-42") works fine. If you need to accept negative numbers, check whether the first character is a minus sign, then call isdigit() on the rest of the string.

Converting strings in different number systems

By default, int() assumes your string represents a number in base 10 (decimal). If your string represents a number in a different base, pass that base as a second argument to int().

int("1010", 2) converts the binary string "1010" to the decimal integer 10. int("FF", 16) converts the hexadecimal string "FF" to the decimal integer 255. The second argument tells int() which base the input string uses.

You can use any base from 2 to 36. Bases higher than 10 use letters: hexadecimal (base 16) uses 0–9 and A–F, for example. The letters can be uppercase or lowercase.

Handling strings with decimal points

int() does not accept strings with decimal points. int("42.5") raises a ValueError because of the period. If your string represents a decimal number and you need an integer, convert to a float first, then to an integer.

int(float("42.5")) works: it converts "42.5" to the float 42.5, then truncates it to the integer 42. Truncation means the decimal part is discarded, not rounded. int(float("42.9")) also returns 42, not 43.

If you need rounding instead of truncation, use the round() function: round(float("42.5")) returns 42 (Python rounds 0.5 to the nearest even number), and round(float("42.6")) returns 43.

Converting user input from input() or a form

When you read input from a user — whether through input() in a script or from a web form — the data arrives as a string, even if the user typed only numbers. You must convert it with int() before you can use it in math or comparisons.

Always wrap this conversion in a try-except block, because you cannot control what the user types. A user might type "abc" when you ask for a number, and your program should handle that gracefully instead of crashing.

user_input = input("Enter a number: ") try:   number = int(user_input)   print(f"You entered {number}") except ValueError:   print("Please enter a valid number")

Common mistakes and how to avoid them

Forgetting that int() truncates rather than rounds is a frequent source of bugs. If you need rounding, call round() on the float first. Another mistake is passing a string with leading or trailing spaces to int() and assuming it will fail — it will not, because int() strips whitespace automatically.

A third mistake is trying to convert a string that contains commas, like "1,000". int("1,000") raises a ValueError. If your string has commas, remove them first: int("1,000".replace(",", "")) converts the string to "1000" and then to the integer 1000.

Finally, remember that int() returns a new integer — it does not change the original string. Strings in Python are immutable, meaning they cannot be changed. int("42") creates a new integer object; the string "42" remains a string.

Frequently Asked Questions

What is the difference between int() and float()?

int() converts to a whole number with no decimal part. float() converts to a number that can have a decimal part. int("42.5") fails, but float("42.5") succeeds and returns 42.5. Use int() when you need a whole number, and float() when you need decimals.

Can I convert a string to an integer if it has a plus sign at the beginning?

Yes. int("+42") works and returns 42. Python treats a leading plus sign the same way it treats a leading minus sign — both are stripped and processed correctly.

What does the base parameter do in int()?

The base parameter tells int() which number system the string uses. int("1010", 2) interprets "1010" as binary (base 2) and returns 10 in decimal. Without a base parameter, int() assumes base 10.

How do I convert a string with commas like "1,000,000"?

Use the replace() method to remove commas first: int("1,000,000".replace(",", "")). This converts the string to "1000000" and then to the integer 1000000.

Should I use try-except or isdigit() to check if a string is a valid number?

Try-except is more robust because it catches all conversion errors, including edge cases like leading plus signs. isdigit() is faster for straightforward cases where you only accept positive integers, but it rejects valid inputs like "-42". Use try-except when you are not sure what the user will enter.