How to check if a string is a number in Python

A string containing a number is valid if it only consists of digits with at most one decimal point. For example, the string “1.23” contains a valid number while “1.2.3” does not.

Solution for How to check if a string is a number in Python : You can use str.isdigit() to check if a string is a number Since a valid number will at most contain one decimal point “.”, first use str.replace(old, new, count) with str containing a possible number, “.” as old, “” as new, and 1 as count to replace up to one decimal point “.” with “” in str. Call str.isdigit() with str as the previous result to return True when every character in str is a digit.

not_a_number = "1.2.3"


how-to-check-if-a-string-is-a-number-in-python