亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

大寫備用字母

大寫備用字母

呼喚遠方 2021-04-09 06:58:17
我想為任何給定的單詞寫一個備用的大寫字母。所以我創建下面的函數。但是問題在于它不返回任何值。相反,我覺得它陷入了無限循環。def farrange(word):finaloutput = ''i = 0for i in word:    if i%2 == 0:        finaloutput = finaloutput + word[i].upper()            else:                    finaloutput = finaloutput + word[i].lower()        i = i + 1   return finaloutput我知道還有其他方法可以解決問題。我使用了另一種元組拆包的方式。但是我想知道為什么會這樣嗎?
查看完整描述

3 回答

?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

您i既用作循環變量(遞增整數),又用作容納字符串的變量。這就是為什么它不起作用。嘗試使用此功能的固定代碼:


finaloutput = ''

i = 0

for e in word:

    if i%2 == 0:

        finaloutput = finaloutput + e.upper()        

    else:            

        finaloutput = finaloutput + e.lower()    

    i = i + 1   

return finaloutput

您還可以進行列表理解:


''.join([e.lower() if c%2 else e.upper() for c,e in enumerate(a)])


查看完整回答
反對 回復 2021-04-13
?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

問題是您要遍歷單詞并將其字母用作索引,這樣可以解決此問題:


def farrange(word):

    finaloutput = ''

    for i, l in enumerate(word):

        if i%2 == 0:

            finaloutput += l.upper()        

        else:            

            finaloutput += l.lower()    

return finaloutput

例如,一種更pythonic的方式:


def arrange(word):

    op = (

        str.upper,

        str.lower

    )

    return "".join(op[x%2](l) for x, l in enumerate(word))


查看完整回答
反對 回復 2021-04-13
?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

謝謝大家的解釋和快捷方式!如果我使用while循環怎么辦?


def farrange(word):

finaloutput = ''

i = 0

while i < len(word):

    if i%2 == 0:

        finaloutput = finaloutput + word[i].upper()        

    else:

        finaloutput = finaloutput + word[i].lower()

    i = i + 1 

return finaloutput

print(farrange("abc")


在這種情況下,我將i用作循環變量,并且它的相同值將作為單詞的索引。因此,我認為這應該可行,但是這次,我只得到第一封信。沒有其他的。為了檢查計數器是否沒有卡在while循環中,我將while條件更改為,while i < 3.但是沒有用。再次返回輸出為a。


查看完整回答
反對 回復 2021-04-13
  • 3 回答
  • 0 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號