Borislav Hadzhiev
Last updated: Jul 13, 2022
Check out my new book
To check if a string can be converted to an integer:
int()
class in a try/except
block.try
block will fully run.ValueError
in the except
block.def can_convert_to_int(string): try: int(string) return True except ValueError: return False print(can_convert_to_int('1357')) # 👉️ True print(can_convert_to_int('-1357')) # 👉️ True print(can_convert_to_int('1.357')) # 👉️ False print(can_convert_to_int('ABC123')) # 👉️ False
We used a try/except
block to check if a string can be converted to an
integer.
try
block succeeds, the function returns True
and the string can be converted to an integer.If calling the int()
class with the string fails, a ValueError
is raised and
the function returns False
.
try/except
statement in this manner is commonly known as "asking for forgiveness rather than permission".We pass the string to the int()
class not knowing whether the conversion will
be successful, and if a ValueError
error is raised, we handle it in the
except
block.
Alternatively, you can use the str.isdigit()
method.
Use the str.isdigit()
method to check if a string can be converted to an
integer, e.g. if my_str.isdigit():
. If the str.isdigit
method returns
True
, then all of the characters in the string are digits and it can be
converted to an integer.
my_str = '1357' if my_str.isdigit(): my_int = int(my_str) print(my_int) # 👉️ 1357 print('✅ string can be converted to integer') else: print('⛔️ string CANNOT be converted to integer')
We used the str.isdigit()
method to check if a string can safely be converted
to an integer.
The str.isdigit
method returns True
if all characters in the string are digits and there is at
least 1 character, otherwise False
is returned.
The method checks if all characters in the string are digits, so if the string
had a minus sign or a decimal, it would return False
.
my_str = '-1357' if my_str.isdigit(): my_int = int(my_str) print(my_int) print('✅ string can be converted to integer') else: # 👇️ this runs print('⛔️ string CANNOT be converted to integer')
try/except
example instead, as it also covers negative integers.If you just want to try converting the string to an integer and silence/ignore
the ValueError
if the conversion fails, use a pass
statement.
my_str = '2468' try: my_int = int(my_str) print(my_int) # 👉️ 2468 except ValueError: pass
The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.
class Employee: pass