Python – 查找包含字母和数字的单词
有时,在使用Python字符串时,我们可能会遇到需要提取某些同时包含数字和字母的单词的问题。这种问题可能发生在许多领域,如学校编程和网络开发。让我们讨论可以执行此任务的某些方式。
方法 #1:使用any() + isdigit() + isalpha()
上述功能的组合可用于执行此任务。在此,我们迭代所有单词并使用isdigit()
和 isalpha() 检查所需的组合。
# Python3 code to demonstrate working of
# Words with both alphabets and numbers
# Using isdigit() + isalpha() + any()
# initializing string
test_str = 'geeksfor23geeks is best45 for gee34ks and cs'
# printing original string
print("The original string is : " + test_str)
# Words with both alphabets and numbers
# Using isdigit() + isalpha() + any()
res = []
temp = test_str.split()
for idx in temp:
if any(chr.isalpha() for chr in idx) and any(chr.isdigit() for chr in idx):
res.append(idx)
# printing result
print("Words with alphabets and numbers : " + str(res))
输出 :
The original string is : geeksfor23geeks is best45 for gee34ks and cs
Words with alphabets and numbers : [‘geeksfor23geeks’, ‘best45’, ‘gee34ks’]
方法#2:使用正则表达式
这是我们可以执行此任务的另一种方式。在此,我们将字符串提供给findall()
,并提取所需的结果。仅返回字符串直到数字。
# Python3 code to demonstrate working of
# Words with both alphabets and numbers
# Using regex
import re
# initializing string
test_str = 'geeksfor23geeks is best45 for gee34ks and cs'
# printing original string
print("The original string is : " + test_str)
# Words with both alphabets and numbers
# Using regex
res = re.findall(r'(?:\d+[a-zA-Z]+|[a-zA-Z]+\d+)', test_str)
# printing result
print("Words with alphabets and numbers : " + str(res))
输出 :
The original string is : geeksfor23geeks is best45 for gee34ks and cs
Words with alphabets and numbers : [‘geeksfor23’, ‘best45’, ‘gee34’]