簡體   English   中英

在Python中的字符串中查找元音的位置

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM