note.nkmk.me

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

Posted: 2021-01-16 / Tags: Python, String

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

This article describes the following contents.

  • Check if a string contains only decimal: str.isdecimal()
  • Check if a string contains only digits: str.isdigit()
  • Check if a string contains only numeric: str.isnumeric()
  • Check if a string contains only alphabetic: str.isalpha()
  • Check if a string contains only alphanumeric: str.isalnum()
  • Check if a string contains only ASCII: str.isascii()
  • Check if a string is empty
  • Check if a string is a number (= can be converted to numeric value)

For methods other than isascii(), empty strings and strings containing symbols (,, ., -, etc.) return False. The last section describes how to check -1.23, for example, is a numerical value.

See the following article for how to convert a string str to numbers int and float.

Sponsored Link

Check if a string contains only decimal: str.isdecimal()

isdecimal() returns True if all characters are decimal characters that is in the Unicode general category Nd. CJK fullwidth numbers are also determined to be 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

A string containing symbols such as - and . is determined to be 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

If you want to determine a string such as '-1.23' as a number, you can use exception handling. It is described in the last section.

Check if a string contains only digits: str.isdigit()

isdigit() returns True not only for characters that are True with isdecimal() but also for characters whose Unicode property value Numeric_Type is Digit or Decimal.

For example, the superscript number ² ('\u00B2') is 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 contains only numeric: str.isnumeric()

isnumeric() returns True not only for characters that are True with isdigit() but also for characters whose Unicode property value Numeric_Type is Numeric.

Vulgar fractions, Roman numerals, Chinese numerals, etc. are also determined as True.

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 contains only alphabetic: str.isalpha()

isalpha() returns True if all characters in the string are alphabetic. Alphabetic characters are those characters defined in the Unicode character database as Letter, i.e., those with general category property being one of Lm, Lt, Lu, Ll, or Lo.

Not only Latin alphabet, but also characters of other languages, such as Japanese hiragana, are determined as 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
Sponsored Link

Check if a string contains only alphanumeric: str.isalnum()

isalnum() returns True if each character is True with one of the methods listed so far, isdecimal(), isdigit(), isnumeric(), and isalpha().

Since each character is evaluated individually, a string containing alphabetic and numeric is determined as True in isalnum() even if 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 contains only ASCII: str.isascii()

In Python 3.7, isascii() was added. isascii() returns True if all characters in the string are ASCII characters (U+0000 - U+007F).

Symbols such as + and - are also determined as True.

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

Hiragana, etc., which are not ASCII, are determined as False.

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

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

Check if a string is empty

The empty string '' is determined as True by isascii() and as 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 whether a string is empty or not. It returns False for an empty string and True for others.

print(bool(''))
# False

print(bool('abc123'))
# True

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

A negative number or decimal value contains . or -, so they are determined as False for methods other than isascii().

Although isascii() returns True, it is not suitable for checking if a string is a number (= can be converted to a numeric value), because it returns True even if other symbols or alphabets 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

A string str can be converted to a floating point number with float(). An error is raised for strings that cannot be converted to numbers.

print(float('-1.23'))
# -1.23

print(type(float('-1.23')))
# <class 'float'>

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

With exception handling, you can define a function that returns True when a string can be converted with 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 want to determine the string containing the digit group separator as True, use replace() to remove them by replacing , with the 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.

Sponsored Link
Share

Related Categories

Related Articles