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')
第一个示例使用 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
# ✅ 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 方法返回一个匹配对象。
我们传递给 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)。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。