[英]Find position of vowels in a string in Python
我正在尝试处理一些Python代码,其中提示有人输入文本字符串。 然后,我需要找到字符串中所有元音的位置。 我有这个,但是没用...
userInput = (input("Enter a line of text: ")
vowels = ("aeiouAEIOU")
position = 0
for char in userInput :
if char in vowels :
position = userInput.find(vowels)
print(char, position)
它返回元音,但每个位置为-1。 我究竟做错了什么? 我已经读到可以使用index函数,但是已经有几个星期了。 关于此代码的简单修复有什么建议吗? 谢谢!!
您的代码有错误,当你做userInput.find(vowels)
记住,字符串vowels
是"aeiouAEIOU"
,这样就不会发现,除非要么串"aeiouAEIOU"
是userInput
。 相反,最好enumerate
并返回这些索引。
userInput = input("Enter a line of text: ")
vowels = "aeiouAEIOU"
for i, char in enumerate(userInput):
if char in vowels:
print(char, i)
您可以使用列表理解并枚举:
positions = [i for i, char in enumerate(userInput) if char in vowels]
这将为您提供元音索引的列表-它将您的用户输入字符串枚举为带有索引的字符列表,并应用谓词-在这种情况下,如果字符不是元音。
验证char in vowels
的测试char in vowels
,您当前正在读取的是元音的字母char
,此时可以直接输出它。 另一方面,您需要通过每次移动到下一个char
时将其递增来记住该位置:
userInput = "This is some input from the user"
vowels = "aeiouAEIOU"
position = 0
for char in userInput:
if char in vowels:
print(char, position)
position += 1
可以将这段代码改进为更多的Python语言,使用enumerate
可以使您免于手动跟踪位置:
serInput = "This is some input from the user"
vowels = "aeiouAEIOU"
for position, char in enumerate(userInput):
if char in vowels :
print(char, position)
可以做出另一个改进,这次我们可以改进性能。 检查char in vowels
时间成本与字符串vowels
的大小成正比。 另一方面,您可以将vowels
的类型从string
更改为set
,以固定时间检查项目是否为set的一部分:
userInput = "This is some input from the user"
vowels = set("aeiouAEIOU")
for pos, char in enumerate(userInput):
if char in vowels:
print(char, pos)
string find(str,str, beg=0, end=len(string))
方法确定字符串str是出现在字符串中还是出现在字符串的子字符串中(如果给出了起始索引beg和结束索引end)。 在您的代码userInput.find(vowels)
,它将检查userInput是否包含完整的元音串,即“ aeiouAEIOU”。 因此可以对代码进行如下改进:
userInput = (input("Enter a line of text: ")
vowels = ("aeiouAEIOU")
position = 0
for char in userInput :
if char in vowels :
position = userInput.find(char)
print(char, position)
尝试以下代码,它与您的代码相似:
userInput = input("Enter a line of text: ")
vowels = "aeiouAEIOU"
for count in userInput:
x = 9 #there are 10 vowels, from 0 to 9
while x >= 0:
if count == vowels[x]:
print("\n",count)
x -= 1
print("\n Done")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.