Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if string starts with a number with Python?

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?

like image 525
Illusionist Avatar asked Apr 07 '11 07:04

Illusionist


People also ask

How do you check if a string starts with a number?

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.

How do you check if the first letter of a string is digit in Python?

Python String isdigit() The isdigit() method returns True if all characters in a string are digits. If not, it returns False .

How do you check if a string starts with a certain character in Python?

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.

How do you check if a string has an integer Python?

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.


1 Answers

Python's string library has isdigit() method:

string[0].isdigit() 
like image 140
plaes Avatar answered Nov 02 '22 00:11

plaes