マニュアルを参照してください
方法の周りにあなたのコードをビルドします。
# 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で指摘されているように、これは文字列中の母音の最初の出現箇所のみを見つけます。これは、2つの理由からです:
戻るところ、文字列内の最小インデックス:
- 各母音が一度だけ
str.find()
テストされているのみ(RFINDも参照())左端の一致を検出部分文字列subは、スライスs [start:end]内にあります。
それを動作させるために、次のようにだから私は無駄にコードを複雑:
# 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
私はそれを母音の位置を返すようにしようとしていました。私はそれが完全ではないことを知っている私はちょうど次に何をするかについて混乱しています。 –
はい、コードはエラーメッセージを生成します。あなたはそれらのメッセージを述べたり、質問したりしません。彼らはあなたの問題を解決するのに役立つ "間違った"情報よりもずっと多くの情報を提供します。関数を間違って使用します。ドキュメンテーションでは、doと使用方法を正確に説明しています。彼らは 'word'を探すために一つの引数を取るだけです。あなたはその出力を使用しません。私の答えを見て、それを受け入れてください。 – handle