检查文档
围绕打造方法你的代码:
# characters to look for in a list (string would work as well)
vowels = ["a","i","o","u","e","y"]
# a function (method)
def vowel_indices(word):
# prepare empty list to collect the positions in
hits = []
# test every of your vowels
for vowel in vowels:
# the function returns the index of vowel in word or -1 if it's not there
pos = word.find(vowel)
# test for match
if pos>0:
# collect match in list
hits.append(pos)
# done, return the list
return hits
# the string to analyse
word = "super"
# pass the string to the method and get its return value
results = vowel_indices(word)
# output the return value
print(results)
输出:
[1, 3]
这实际上是一个列表对象,但是Python会打印它的元素。
正如@PM 2Ring所指出的那样,这只发现字符串中元音的第一次出现。这有两个原因:
- 每个元音只测试一次
str.find()
只能找到最左边的匹配(见RFIND()):
返回指数最低的字符串,其中在在切片s [start:end]内找到子字符串sub。
所以我毫无意义的复杂如下,使其工作代码:
# characters to look for in a list (string would work as well)
vowels = ["a","i","o","u","e","y"]
# a function (method)
def vowel_indices(word):
# prepare empty list to collect the positions in
hits = []
# test every of your vowels
for vowel in vowels:
# work on a copy
temp = word
# look first, give up later
while True:
# the function returns the index of vowel in word or -1 if it's not there
pos = temp.lower().find(vowel)
# test for match
if pos>0:
# collect match in list
hits.append(pos)
# remove matched vowel from
temp = temp[:pos] + " " + temp[pos+1:]
print(temp)
else:
break
# done, return the list
return hits
# the string to analyse
word = "Banana!"
# pass the string to the method and get its return value
results = vowel_indices(word)
# output the return value
print(results)
输出
B nana!
B n na!
B n n !
[1, 3, 5]
此代码不能运行。你期望它做什么(打印,退货)? – handle
我试图让它返回元音的位置。我知道这并不完整,我只是对接下来要做的事感到困惑。 –
是的,但是你的代码会产生错误信息。你不会陈述那些消息或询问他们。他们提供比“错误”更多的信息来帮助您解决问题。您错误地使用了这些功能。文档告诉你到底做了什么以及如何使用它们。他们只需要一个参数来寻找“单词”。你不使用他们的输出。请看我的答案,并请接受它。 – handle