2017-09-24 89 views
-2

研究分配(使用python-3):查找和打印元音

對於學習任務,我需要編寫打印所有元音的指標在一個字符串的程序,最好使用「而循環」。 到目前爲止,我已經成功地設計了一個「for循環」來完成這項工作,但我可以肯定需要在「while循環」

for循環的解決方案有所幫助:

string = input("Typ in a string: ") 
vowels = "a", "e", "i", "o", "u" 
indices = "" 

for i in string: 
    if i in vowels: 
     indices += i 
print(indices) 

while循環溶液:

string = input("Typ in a string: ") 
vowels = "a", "e", "i", "o", "u" 
indices = "" 

while i < len(string): 
    <code> 
    i += 1 
print(indices) 

會使用'指數()''查找()'在這裏工作?

回答

0

您可以通過做string[x]獲得字符串索引x處的字符!

i = 0 # initialise i to 0 here first! 
while i < len(string): 
    if string[i] in vowels: 
     indices += str(i) 
    i += 1 
print(indices) 

然而,正在indices一個str真的適合?我不這麼認爲,因爲你們之間沒有分隔符。字符串"12"是否意味着索引1和2處有2個元音,或者是一個元音索引12?您可以嘗試使用一個列表來存儲索引:

indices = [] 

而且你可以通過執行添加i它:

indices.append(i) 

順便說一句,你的for循環解決方案將打印元音字符,而不是指數。

如果您不想使用列表,也可以在每個索引後面添加一個額外的空格。

indices += str(I) + " " 
+0

謝謝掃地!難點在於我還沒有學會如何使用列表,接下來的兩章是元組和列表。我真的仍然很難創造性地使用我們迄今學到的「工具」(這些工具包括:表達式,變量,條件,迭代,函數和當前章節的字符串)但我理解你的解釋,謝謝你的支持幫幫我! – GJ01

+0

@ GJ01我編輯了答案。 *有*解決方法。 – Sweeper

+0

太棒了!非常感謝! :-)你對'元音'和'索引'也是正確的,但我不知道如何返回索引。 – GJ01

0

試試這個:

string = input("Typ in a string: ") 
    vowels = ["a", "e", "i", "o", "u"] 




     higher_bound=1 
     lower_bound=0 

     while lower_bound<higher_bound: 
      convert_str=list(string) 
      find_vowel=list(set(vowels).intersection(convert_str)) 
      print("Vowels in {} are {}".format(string,"".join(find_vowel))) 

      lower_bound+=1 

您還可以設置higher_bound爲len(字符串),那麼它就會打印結果多次字符串LEN。

既然這是你的研究任務,你應該看看和練習自己,而不是複製粘貼。下面是解決方案的其他信息:

在數學中,交點A∩兩個集合A的B和B是包含A的所有元素也屬於B(或 等效地設定 ,的所有元素B也屬於A),但沒有其他 元素。有關本文中使用的符號的說明,請參閱數學符號表中的 。

在蟒蛇:

在Python路口()的語法是:

A.intersection(* other_sets)

A = {2, 3, 5, 4} 
B = {2, 5, 100} 
C = {2, 3, 8, 9, 10} 

print(B.intersection(A)) 
print(B.intersection(C)) 
print(A.intersection(C)) 
print(C.intersection(A, B)) 
+0

謝謝保羅!真的很有趣的解決方案,但我還沒有那麼先進。將到達那裏,但也許不是今天;-) – GJ01