I have a string which is like: t = '²'
This throws my code off: int(t)
with the error:
ValueError: invalid literal for int() with base 10: '²'
How do I detect if a string is a superscript and not a real integer?
I just want to cast a string number to int and get the integer. I want to make sure that the numbers I pass doesn't throw the above error.
I don't want to use try/except
block.
CodePudding user response:
The is_digit
method returns True
for subscripts and superscripts. You can use a combination of int
and is_digit
to implement that:
def is_subscript(s):
if s.isdigit():
try:
int(s)
except ValueError:
return True
return False
Then
print(is_subscript('²')) # Should print True
print(is_subscript('2')) # Should print False
CodePudding user response:
You need to translate the string like this
SUP = str.maketrans("⁰¹²³⁴⁵⁶⁷⁸⁹","0123456789")
t = '²'
print(int(t.translate(SUP)))
CodePudding user response:
You can use .isdecimal()
for testing. Unlike .isnumeric()
and .isdigit()
, it does not recognize '²', etc. as a digit:
"²".isdecimal()
# False
"2".isdecimal()
#True