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
请注意
,对于负数(它们包含负号)和浮点数(它们包含句点),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)。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。