我正在编写一个函数,它将一个单词作为参数并查看每个字符,如果单词中有一个数字,它将返回该单词
这是我将遍历“让我们看看 pg11”的字符串。我想查看每个单词中的每个字符,如果单词中有数字,我想按原样返回单词。
import string
def containsDigit(word):
for ch in word:
if ch == string.digits
return word
我正在编写一个函数,它将一个单词作为参数并查看每个字符,如果单词中有一个数字,它将返回该单词
这是我将遍历“让我们看看 pg11”的字符串。我想查看每个单词中的每个字符,如果单词中有数字,我想按原样返回单词。
import string
def containsDigit(word):
for ch in word:
if ch == string.digits
return word
if any(ch.isdigit() for ch in word):
print word, 'contains a digit'
要使您的代码正常工作,请使用in
关键字(它将检查项目是否在序列中),在 if 语句后添加一个冒号,并缩进您的 return 语句。
import string
def containsDigit(word):
for ch in word:
if ch in string.digits:
return word
为什么不使用正则表达式?
>>> import re
>>> word = "super1"
>>> if re.search("\d", word):
... print("y")
...
y
>>>
因此,在您的功能中,只需执行以下操作:
import re
def containsDigit(word):
if re.search("\d", word):
return word
print(containsDigit("super1"))
输出:
'super1'
您缺少一个冒号:
for ch in word:
if ch.isdigit(): #<-- you are missing this colon
print "%s contains a digit" % word
return word
通常,当您想知道“某物”是否包含“某物”时,集合可能会很有用。
digits = set('0123456789')
def containsDigit(word):
if set(word) & digits:
return word
print containsDigit('hello')
If you desperately want to use the string
module. Here is the code:
import string
def search(raw_string):
for raw_array in string.digits:
for listed_digits in raw_array:
if listed_digits in raw_string:
return True
return False
If I run it in the shell here I get the wanted resuts. (True if contains. False if not)
>>> search("Give me 2 eggs")
True
>>> search("Sorry, I don't have any eggs.")
False
The string.digits is a string. If we loop through that string we get a list of the parent string broke down into pieces. Then we get a list containing every character in a string with'n a list. So, we have every single characters in the string! Now we loop over it again! Producing strings which we can see if the string given contains a digit because every single line of code inside the loop takes a step, changing the string we looped through. So, that means ever single line in the loop gets executed every time the variable changes. So, when we get to; for example 5. It agains execute the code but the variable in the loop is now changed to 5. It runs it agin and again and again until it finally got to the end of the string.