Check if string is numeric python

Check if a string is numeric, alphabetic, alphanumeric, or ASCII

Python provides various methods to check if the characters in the string ( str ) are numeric, alphabetic, alphanumeric, or ASCII.

For information on converting a numeric string ( str ) into a numeric value ( int or float ), or determining the case (upper or lower) of letters, refer to the following articles.

Check if a string is decimal: str.isdecimal()

The isdecimal() method returns True if all characters in the string are decimal characters that fall under the Nd category in Unicode. Fullwidth numbers in CJK languages are also considered True .

s = '1234567890' print('s =', s) print('isdecimal:', s.isdecimal()) print('isdigit:', s.isdigit()) print('isnumeric:', s.isnumeric()) # s = 1234567890 # isdecimal: True # isdigit: True # isnumeric: True s = '1234567890' print('s =', s) print('isdecimal:', s.isdecimal()) print('isdigit:', s.isdigit()) print('isnumeric:', s.isnumeric()) # s = 1234567890 # isdecimal: True # isdigit: True # isnumeric: True 

For isdecimal() , strings that include symbols such as — and . are evaluated as False .

s = '-1.23' print('s =', s) print('isdecimal:', s.isdecimal()) print('isdigit:', s.isdigit()) print('isnumeric:', s.isnumeric()) # s = -1.23 # isdecimal: False # isdigit: False # isnumeric: False 

To recognize a numeric string like ‘-1.23’ as valid, you can implement exception handling as detailed in the final section.

Читайте также:  Embed style in html head

Check if a string is digits: str.isdigit()

The isdigit() method returns True for characters that are True with isdecimal() and for characters with the Unicode property value Numeric_Type set to Digit or Decimal .

For example, the superscript number ² ( ‘\u00B2’ ) is evaluated as False in isdecimal() , but True in isdigit() .

s = '10\u00B2' print('s =', s) print('isdecimal:', s.isdecimal()) print('isdigit:', s.isdigit()) print('isnumeric:', s.isnumeric()) # s = 10² # isdecimal: False # isdigit: True # isnumeric: True 

Check if a string is numeric: str.isnumeric()

The isnumeric() method returns True for characters that are True with isdigit() and for characters with the Unicode property value Numeric_Type set to Numeric .

Vulgar fractions, Roman numerals, Chinese numerals, and others are also determined as True under isnumeric() .

s = '\u00BD' print('s =', s) print('isdecimal:', s.isdecimal()) print('isdigit:', s.isdigit()) print('isnumeric:', s.isnumeric()) # s = ½ # isdecimal: False # isdigit: False # isnumeric: True s = '\u2166' print('s =', s) print('isdecimal:', s.isdecimal()) print('isdigit:', s.isdigit()) print('isnumeric:', s.isnumeric()) # s = Ⅶ # isdecimal: False # isdigit: False # isnumeric: True s = '一二三四五六七八九〇' print('s =', s) print('isdecimal:', s.isdecimal()) print('isdigit:', s.isdigit()) print('isnumeric:', s.isnumeric()) # s = 一二三四五六七八九〇 # isdecimal: False # isdigit: False # isnumeric: True 

Check if a string is alphabetic: str.isalpha()

The isalpha() method determines if all characters in the string belong to the alphabetic category, i.e., those with a Unicode character database general category property of Lm , Lt , Lu , Ll , or Lo .

This not only includes the Latin alphabet but also characters from other languages, such as Japanese hiragana, all of which are considered True .

s = 'abc' print('s =', s) print('isalpha:', s.isalpha()) # s = abc # isalpha: True s = 'あいうえお' print('s =', s) print('isalpha:', s.isalpha()) # s = あいうえお # isalpha: True 

Check if a string is alphanumeric: str.isalnum()

The isalnum() method returns True if all characters pass any of the previously mentioned methods, namely isdecimal() , isdigit() , isnumeric() , or isalpha() .

Since each character is evaluated individually, a string with a mix of alphabetic and numeric characters will be evaluated as True in isalnum() even if it is False in all other methods.

s = 'abc123' print('s =', s) print('isalnum:', s.isalnum()) print('isalpha:', s.isalpha()) print('isdecimal:', s.isdecimal()) print('isdigit:', s.isdigit()) print('isnumeric:', s.isnumeric()) # s = abc123 # isalnum: True # isalpha: False # isdecimal: False # isdigit: False # isnumeric: False 

Check if a string is ASCII: str.isascii()

The isascii() method returns True if all characters in the string are ASCII characters (U+0000 — U+007F).

Symbols such as + and — are also determined as True under isascii() .

s = 'abc123+-,.&' print('s =', s) print('isascii:', s.isascii()) print('isalnum:', s.isalnum()) # s = abc123+-,.& # isascii: True # isalnum: False 

Non-ASCII characters are determined as False .

s = 'あいうえお' print('s =', s) print('isascii:', s.isascii()) print('isalnum:', s.isalnum()) # s = あいうえお # isascii: False # isalnum: True 

Unlike other methods, isascii() returns True even for empty strings, as explained in the next section.

Check if a string is empty

The empty string » is considered True by isascii() , while considered False by other methods.

s = '' print('s =', s) print('isalnum:', s.isalnum()) print('isalpha:', s.isalpha()) print('isdecimal:', s.isdecimal()) print('isdigit:', s.isdigit()) print('isnumeric:', s.isnumeric()) print('isascii:', s.isascii()) # s = # isalnum: False # isalpha: False # isdecimal: False # isdigit: False # isnumeric: False # isascii: True 

Use bool() to check if a string is empty. It returns False for an empty string and True for non-empty strings.

print(bool('')) # False print(bool('abc123')) # True 

Check if a string is a number (= can be converted to numeric value)

Negative numbers or decimal values contain symbols like . or — . Hence, they are evaluated as False by all methods, except isascii() .

Although isascii() returns True , it is not suitable for verifying if a string is a number (i.e., can be converted to a numeric value) because it also returns True even when other symbols or letters are included.

s = '-1.23' print('s =', s) print('isalnum:', s.isalnum()) print('isalpha:', s.isalpha()) print('isdecimal:', s.isdecimal()) print('isdigit:', s.isdigit()) print('isnumeric:', s.isnumeric()) print('isascii:', s.isascii()) # s = -1.23 # isalnum: False # isalpha: False # isdecimal: False # isdigit: False # isnumeric: False # isascii: True 

You can convert a string into a floating-point number using float() . However, keep in mind that this will result in an error if you attempt to convert non-numeric strings, such as ‘abc’ .

print(float('-1.23')) # -1.23 print(type(float('-1.23'))) # # print(float('abc')) # ValueError: could not convert string to float: 'abc' 

By implementing exception handling, you can define a function that returns True if a string can successfully be converted using float() .

def is_num(s): try: float(s) except ValueError: return False else: return True print(is_num('123')) # True print(is_num('-1.23')) # True print(is_num('+1.23e10')) # True print(is_num('abc')) # False print(is_num('10,000,000')) # False 

If you need to treat a string with separators ( , ) as numeric, use the replace() method to remove separators by replacing , with an empty string » .

def is_num_delimiter(s): try: float(s.replace(',', '')) except ValueError: return False else: return True print(is_num_delimiter('10,000,000')) # True 

You can also use replace() for whitespace separators.

def is_num_delimiter2(s): try: float(s.replace(',', '').replace(' ', '')) except ValueError: return False else: return True print(is_num_delimiter2('10,000,000')) # True print(is_num_delimiter2('10 000 000')) # True 

If you want to check whether a number is an integer or a decimal, see the following article.

Источник

e Learning

Learn How to Check if a String Is a Number in Python 3

In this tutorial, we will learn how to check if a string is a number in the Python 3 programming language.

Learn How to Check if a String Is a Number in Python 3

Python 3 has a built-in string function called str.isnumeric() which will check whether a string is numeric or not. However, the str.isnumeric() function will return False for floating-point numbers. To check if a string is a float, we can use a try-except statement.

Python is string numeric

Python str.isnumeric() function will return True if the given string is numeric or return False otherwise.

Example 1

The Above python code will return True since “10” is a numeric value.

Example 2

The Above python code will return False .

We can also use the isnumeric() function with a string variable as follows.

number = "100" print(number.isnumeric())

To return True , the whole string has to be numbers only, or it will return False . For Example, the following code will return False since the variable number contains the letter “A”.

number = "100A" print(number.isnumeric())

Check if a string is a Float in Python 3

Python str.isnumeric() function will return False for the floating-point numbers. But we can write a simple function using the try-except statement to check whether a string is a floating-point number or not.

def is_number(string): try: float(string) return True except ValueError: return False

As per the above python code, we created a new function called is_number() . The Function will simply try to convert the given string to a float. If the string can be converted to float, then the is_number function will return True .

Example

def is_number(string): try: float(string) return True except ValueError: return False print(is_number("10.5"))

The Above Python Code will return True .

Summary

In this tutorial, we learned how to check if a string is a number in python programming.

  • We used the python str.isnumeric() function to check whether a string is numeric or not.
  • To check Floating point numbers, we wrote a simple python function called is_number() .

Источник

Оцените статью