如何在 Python 中检查字符串是否包含数字
本文介绍如何检查 Python 字符串是否包含数字。
如果给定的字符串包含数字,则 Python 内置的 any
函数与 str.isdigit
一起将返回 True
。否则返回 False
。
如果给定的字符串包含数字,则模式为 r'\d'
的 Python 正则表达式搜索方法也可以返回 True
。
如果给定的 Python 迭代对象的任何元素为 True
,则 any
函数返回 True
,否则,返回 False
。
如果给定字符串中的所有字符均为数字,则 str.isdigit()
返回 True
,否则返回 False
。
any(chr.isdigit() for chr in stringExample)
如果 stringExample
至少包含一个数字,那么上面的代码将返回 True
,因为 chr.isdigit() for chr in stringExample
在可迭代对象中至少有一个 True
。
工作示例
str1 = "python1"
str2 = "nonumber"
str3 = "12345"
print(any(chr.isdigit() for chr in str1))
print(any(chr.isdigit() for chr in str2))
print(any(chr.isdigit() for chr in str3))
输出:
True
False
True
Python map(function, iterable)
函数将函数 function
应用于给定可迭代对象的每个元素,并返回一个迭代器产生以上结果。
因此,我们可以将上述解决方案重写为
any(map(str.isdigit, stringExample))
工作示例
str1 = "python1"
str2 = "nonumber"
str3 = "12345"
print(any(map(str.isdigit, str1)))
print(any(map(str.isdigit, str2)))
print(any(map(str.isdigit, str3)))
输出:
True
False
True
re.search(r'\d', string)
函数扫描 string
并返回匹配对象对于与给定模式匹配的第一个位置- \d
,表示在 0 到 9 之间的任何数字,如果找不到匹配项,则返回 None
。
import re
print(re.search(r'\d', "python3.8"))
#output: <re.Match object; span=(6, 7), match='3'>
match
对象包含 2 个元组的 span
,它们是 match
的开始和结束位置,以及匹配的内容,例如 match = '3'
。
bool()
函数可以将 match
对象或 None
的 re.search
结果转换为 True
或 False
。
工作示例
import re
str1 = "python12"
str2 = "nonumber"
str3 = "12345"
print(bool(re.search(r'\d', str1)))
print(bool(re.search(r'\d', str2)))
print(bool(re.search(r'\d', str3)))
输出:
True
False
True
就运行时间而言,正则表达式评估比使用内置的字符串函数要快得多。如果字符串的值相当大,那么 re.search()
比使用字符串函数更理想。
在给定字符串上运行 search()
函数之前,使用 re.compile()
编译表达式,也会使执行时间更快。
将 compile()
的返回值捕获到一个变量中,然后在这个变量中调用 search()
函数。在这种情况下,search()
只需要一个参数,即对照编译后的表达式搜索的字符串。
def hasNumber(stringVal):
re_numbers = re.compile('\d')
return False if (re_numbers.search(stringVal) == None) else True
综上所述,内置函数 any()
和 isdigit()
可以很容易地串联使用,检查一个字符串是否包含一个数字。
然而,在正则表达式模块 re
中使用实用函数 search()
和 compile()
会比内置的字符串函数更快地生成结果。所以,如果你要处理大的数值或字符串,那么正则表达式的解决方案要比字符串函数更理想。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串