對不起,我的問題可能看起來很愚蠢,我對編程很陌生。所以在下面的程式中,我發現很難理解為什么運算式“translation = translation g”實際上用g替換了元音。
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou ":
translation = translation "g"
else:
translation = translation letter
return translation
print(translate(input("type the word you9 wish to translate: ")))
以我有這樣的代碼為例
translation = "dog"
print(translation "g")
這個運算式應該列印出 dogg。那么為什么前面程式中的“ ”號執行的是替換而不是加法呢?
uj5u.com熱心網友回復:
讓我們從頭開始
該行
for letter in phrase:表示將處理單詞中的每個字母。因此,例如,如果輸入字串是 'dog',它將迭代 d、o 和 g 三次。
接下來,線
if letter in "AEIOUaeiou ":
translation = translation "g"
意味著如果一個字母是元音,您將在翻譯后附加 ag,而不是字母中的元音。繼續輸入“dog”作為字串的示例,當字母“o”被處理時,它會將“g”附加到翻譯中。
似乎您想將 g 附加到字串的末尾,這段代碼應該可以正常作業。
ddef translate(phrase):
translation = ""
check_vowel = False
for letter in phrase:
if letter in "AEIOUaeiou ":
check_vowel = True
translation = translation letter
if check_vowel:
translation = translation 'g'
return translation
print(translate(input("type the word you9 wish to translate: ")))
該代碼將檢查元音是否在字串中。如果它在一個字串中,那么它會將 bool 變數 check_vowel 更改為 True。然后它將 g 附加到末尾。順便說一句,這項任務可以通過使用正則運算式輕松完成
import re
input_word = input("type the word you9 wish to translate: ")
if re.search("[aiueoAIUEO]",input_word):
input_word = input_word 'g'
print(input_word)
uj5u.com熱心網友回復:
因為你的else條件。在if未滿足條件,所以它去else哪里翻譯的價值是部分""這是一個空字串。添加g空字串會使您g變得如此簡單。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/368997.html
標籤:蟒蛇-3.x
上一篇:你可以在VisualStudio中開發Desktop(.exe)嗎?
下一篇:如何將滾動條插入充滿按鈕的畫布?
