我想知道如何在不使用正则表达式的情况下在字符串列表中找到双字母的外观。以下是我到目前为止的情况。
word="kookss"
new_words=["laal","mkki"]
def double_letter(word):
for i in range(len(word)-1):
if word[i]== word[i+1]:
return (word[i],word[i+1])
print(double_letter(word))
for w in range(len(new_words)-1):
print(double_letter(new_words))
output :
["OO","ss"]
["aa"]
["kk"]
答案 0 :(得分:2)
word="kookss"
new_words=["laal","mkki"]
def double_letter(word):
# each double letter found should be put in this list.
double_letters = []
for i in range(len(word)-1):
if word[i]== word[i+1]:
double_letters.append(word[i] + word[i+1])
return double_letters
print(double_letter(word))
for w in new_words:
# for each word `w` in list `new_words` call double_letter method
print(double_letter(w))
输出:
['oo', 'ss']
['aa']
['kk']
您的代码无效,因为:
for w in range(len(new_words)-1):
print(double_letter(new_words))
此代码将new_words
(列表)传递给期望单个单词的double_letter
方法。
突然word[i]== word[i+1]
变为"laal" == "mkki"
这是假的,所以你的回报是None
您将同一列表传递两次,因此获得2 None
。