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

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

字符串索引超出范圍問題 - Python

字符串索引超出范圍問題 - Python

牛魔王的故事 2021-10-10 14:02:17
我正在嘗試制作一個有損文本壓縮程序,從輸入中刪除所有元音,除非元音是單詞的第一個字母。我一直在第 6 行收到此“字符串索引超出范圍”錯誤。請幫忙!text = str(input('Message: '))text = (' ' + text)for i in range(0, len(text)):  i = i + 1  if str(text[i-1]) != ' ': #LINE 6    text = text.replace('a', '')    text = text.replace('e', '')    text = text.replace('i', '')    text = text.replace('o', '')    text = text.replace('u', '')print(text)
查看完整描述

3 回答

?
溫溫醬

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

通過用 "" 替換任何字符來縮短字符串長度意味著如果刪除一個字符,則迭代器中使用的 len(text) 比實際字符串長度長。有很多替代解決方案。例如,


text_list = list(text)

for i in range(1, len(text_list)):

    if text_list[i] in "aeiou":

        text_list[i] = ""

text = "".join(text_list)

通過將字符串轉換為其復合字符的列表,您可以刪除字符但保持列表長度(因為允許空元素)然后重新加入它們。


請務必考慮特殊情況,例如 len(text)<2。


查看完整回答
反對 回復 2021-10-10
?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

當您用空格替換字母時,您的單詞會變短。因此len(text),如果您刪除任何字母,最初的內容將超出范圍。但是請注意,replace正在替換字符串中的所有匹配項,因此甚至不需要循環。

使用循環的另一種方法是在循環過程中跟蹤要替換的字母索引,然后在循環完成后進行替換。


查看完整回答
反對 回復 2021-10-10
?
GCT1015

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

正如busybear指出的那樣,循環不是必需的:您的替換不依賴于i.


這是我的做法:


def strip_vowels(s): # Remove all vowels from a string

    for v in 'aeiou':

        s = s.replace(v, '')

    return s


def compress_word(s):

    if not s: return '' # Needed to avoid an out-of-range error on the empty string

    return s[0] + strip_vowels(s[1:]) # Strip vowels from all but the first letter


def compress_text(s): # Apply to each word

    words = text.split(' ')

    new_words = compress_word(w) for w in words

    return ' '.join(new_words)


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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