我正在尝试写一段简单的代码来检查每个字母: a,e,i,o,u在字符串中存在的次数,但我得到的错误是:字符串索引超出范围。我能做些什么来解决这个问题呢?代码是:
def targ6(str6):
x = ['a','e','i','o','u']
s = ""
for tav in str6:
for y in range(len(x)):
if x[y] == tav:
s[y] += 1
for y in range(len(x)):
return ('the letter'+x[tav]+'appears'+s[tav]+'times')
#main
string6=input("enter a string")
print(targ6(string6))发布于 2020-11-29 06:03:22
试试这个:
def targ6(str6):
x = ['a','e','i','o','u']
s = {k:0 for k in x}
for tav in str6:
for y in range(len(x)):
if x[y] == tav:
s[tav] += 1 # s[x[y]] += 1
return s
#main
string6="enter a string"
print(targ6(string6))输出:
{'a': 1, 'e': 2, 'i': 1, 'o': 0, 'u': 0}发布于 2020-11-29 06:01:16
from collections import Counter
def targ6(str6):
list1 = []
x = ['a','e','i','o','u']
for i in str6: #For character in string
if i in x: #If character in vowel list
list1.append(i) #Append the character to a list
for k, v in Counter(list1).items(): #Counter returns a dict with each element's count
print(k, "appears", v, "times in", str6)
string6 = input("enter a string :")
targ6(string6)示例:-
enter a string :Hi How are you? Fine?
i appears 2 times in Hi How are you? Fine?
o appears 2 times in Hi How are you? Fine?
a appears 1 times in Hi How are you? Fine?
e appears 2 times in Hi How are you? Fine?
u appears 1 times in Hi How are you? Fine?发布于 2020-11-29 06:02:23
s),而且它们的工作方式肯定不像计数器之类的。for ... in range(len(...)),请停止你正在做的事情。会有更好的方法。print.return!仔细阅读Python文档,它很容易理解,您不必记住所有内容,只需对事物有个感觉,这样您就知道将来该往哪里看了。def count_vowels(string):
for vowel in 'aeiou':
print('the letter', vowel, 'appears', string.count(vowel), 'times')
input_string = input("enter a string: ")
count_vowels(input_string)https://stackoverflow.com/questions/65054798
复制相似问题