Python 中检查字符串是否仅包含数字

使用 str.isnumeric() 方法检查字符串是否只包含数字,例如 if string.isnumeric():。 如果字符串中的所有字符都是数字,则 str.isnumeric() 方法将返回 True,否则返回 False。

import re


# ✅ 检查字符串是否只包含数字 (str.isnumeric())
my_str = '3468910'
print(my_str.isnumeric())  # ?️ True

if my_str.isnumeric():
    # ?️ This runs
    print('The string contains only numbers')
else:
    print('The string does NOT contain only numbers')

# ---------------------------------------------

# ✅ 检查字符串是否只包含数字 (re.match())

# ?️ <re.Match object; span=(0, 7), match='3468910'>
print(re.match(r'^[0-9]+$', my_str))

if re.match(r'^[0-9]+$', my_str):
    # ?️ this runs
    print('The string contains only numbers')
else:
    print('The string does NOT contain only numbers')

Python 中检查字符串是否仅包含数字

第一个示例使用 str.isnumeric() 方法检查字符串是否仅包含数字。

str.isnumeric 方法如果字符串中的所有字符都是数字,并且至少有一个字符,则返回 True,否则返回 False。

print('5'.isnumeric())  # 👉️ True
print('50'.isnumeric())  # 👉️ True

print('-50'.isnumeric())  # 👉️ False
print('3.14'.isnumeric())  # 👉️ False
print('A'.isnumeric())  # 👉️ False

请注意 ,对于负数(它们包含负号)和浮点数(它们包含句点),str.isnumeric() 方法返回 False。

如果需要检查字符串是有效整数还是有效浮点数,请使用 try/except 语句。

# ✅ Check if a string is a valid integer
def is_integer(string):
    try:
        int(string)
    except ValueError:
        return False
    return True


print(is_integer('359'))  # 👉️ True
print(is_integer('-359'))  # 👉️ True
print(is_integer('3.59'))  # 👉️ False
print(is_integer('3x5'))  # 👉️ False

# ----------------------------------------------

# ✅ Check if a string is a valid float


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


print(is_float('359'))  # 👉️ True
print(is_float('-359'))  # 👉️ True
print(is_float('3.59'))  # 👉️ True
print(is_float('3x5'))  # 👉️ False

如果将字符串转换为整数或浮点数失败,except 块将在我们通过从函数返回 False 来处理 ValueError 的地方运行。

或者,我们可以使用 re.match() 方法。

使用 re.match() 检查字符串是否只包含数字

使用 re.match() 方法检查字符串是否只包含数字,例如 re.match(r'^[0-9]+$', string)。 如果字符串只包含数字,re.match() 方法将返回一个匹配对象,否则返回 None。

import re


def only_numbers(string):
    return re.match(r'^[0-9]+$', string)


# 👇️ <re.Match object; span=(0, 4), match='3590'>
print(only_numbers('3590'))

if only_numbers('3590'):
    # 👇️ this runs
    print('The string contains only numbers')
else:
    print('The string does NOT contain only numbers')

如果提供的正则表达式在字符串中匹配,则 re.match 方法返回一个匹配对象。

如果字符串与正则表达式模式不匹配,则 match() 方法返回 None。

我们传递给 re.match() 方法的第一个参数是一个正则表达式。

import re


def only_numbers(string):
    return re.match(r'^[0-9]+$', string)

方括号 [] 用于表示一组字符。

0-9 字符匹配范围内的数字。

插入符号 ^ 匹配字符串的开头,美元符号 $ 匹配字符串的结尾。

加号 + 使正则表达式匹配前面字符(数字范围)的 1 次或多次重复。

如果要从函数返回布尔结果,请将对 re.match() 的调用传递给 bool() 函数。

import re


def only_numbers(string):
    return bool(re.match(r'^[0-9]+$', string))


print(only_numbers('3590'))  # 👉️ True
print(only_numbers('3x59'))  # 👉️ False

if only_numbers('3590'):
    # 👇️ this runs
    print('✅ The string contains only numbers')
else:
    print('✅ The string does NOT contain only numbers')

bool() 类获取一个值并将其转换为布尔值(True 或 False)。