I have a string that starts with a number (from 0-9) I know I can "or" 10 test cases using startswith() but there is probably a neater solution
so instead of writing
if (string.startswith('0') || string.startswith('2') || string.startswith('3') || string.startswith('4') || string.startswith('5') || string.startswith('6') || string.startswith('7') || string.startswith('8') || string.startswith('9')): #do something
Is there a cleverer/more efficient way?
isDigit() method. The recommended solution is to use the Character. isDigit(char) method to check if the first character of the string is a digit or not.
Python String isdigit() The isdigit() method returns True if all characters in a string are digits. If not, it returns False .
The startswith() string method checks whether a string starts with a particular substring. If the string starts with a specified substring, the startswith() method returns True; otherwise, the function returns False.
To check if a string is integer in Python, use the isdigit() method. The string isdigit() is a built-in Python method that checks whether the given string consists of only digits. In addition, it checks if the characters present in the string are digits or not.
Python's string
library has isdigit()
method:
string[0].isdigit()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With