with positive integers you could use .isdigit:
>>> '16'.isdigit()
True
it doesn't work with negative integers though. suppose you could try the following:
>>> s = '-17'
>>> s.startswith('-') and s[1:].isdigit()
True
it won't work with '16.0' format, which is similar to int casting in this sense.
edit:
def check_int(s):
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
Answer from SilentGhost on Stack Overflowwith positive integers you could use .isdigit:
>>> '16'.isdigit()
True
it doesn't work with negative integers though. suppose you could try the following:
>>> s = '-17'
>>> s.startswith('-') and s[1:].isdigit()
True
it won't work with '16.0' format, which is similar to int casting in this sense.
edit:
def check_int(s):
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
If you're really just annoyed at using try/excepts all over the place, please just write a helper function:
def represents_int(s):
try:
int(s)
except ValueError:
return False
else:
return True
>>> print(represents_int("+123"))
True
>>> print(represents_int("10.0"))
False
It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.
How to think about integers, strings, and floats?
Command basics/ python strings vs integers
how are you supposed to add an integer to a string?
i am a beginner at python and im trying to convert string to int but it doesn't work
Videos
I tried it with isinstance(<var>, int)
But if the string is: '5', it returns False because it's still a string.
If you write isinstance(int(<var>), int), in some cases it works but when the string is 'abc' the string cannot be casted into an integer and an error pops up. With type() it's the same problem.
With:
try:
int( '7.5')
except:
#code
7.5 can get casted into an integer but it's not an actual integer.
So I am taking a intro to python class right now, I'm doing well in it and everything, but I guess I was asleep when they showed the slide telling the difference of integers, strings, and floats lol
I've never been "stuck" with anything because of it, and I am pretty good with excel so I understand stuff with VALUE() being necessary sometimes, as numbers (integers) can be stored as a string. I guess I just don't really know what float means. We've used it for stuff like
print(f"You are {age} years old!")
So I get that adding the f makes python know you are wanting to use that variable reference thing
What's a float?
im new to python and trying to learn how to print the sum of a integer and a string number, i get an error that says| unsupported operand type(s) +: 'int' and 'str' | i dont know how to solve it and everything i look up only has for int + int so im wondering if i have to just convert the string to a integer and if so how would that be done but if thats not what i need to do i would also really appreciate an explanation.