3 回答

TA貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個(gè)贊
通過用 "" 替換任何字符來縮短字符串長(zhǎng)度意味著如果刪除一個(gè)字符,則迭代器中使用的 len(text) 比實(shí)際字符串長(zhǎng)度長(zhǎng)。有很多替代解決方案。例如,
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)
通過將字符串轉(zhuǎn)換為其復(fù)合字符的列表,您可以刪除字符但保持列表長(zhǎng)度(因?yàn)樵试S空元素)然后重新加入它們。
請(qǐng)務(wù)必考慮特殊情況,例如 len(text)<2。

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊
當(dāng)您用空格替換字母時(shí),您的單詞會(huì)變短。因此len(text)
,如果您刪除任何字母,最初的內(nèi)容將超出范圍。但是請(qǐng)注意,replace
正在替換字符串中的所有匹配項(xiàng),因此甚至不需要循環(huán)。
使用循環(huán)的另一種方法是在循環(huán)過程中跟蹤要替換的字母索引,然后在循環(huán)完成后進(jìn)行替換。

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超4個(gè)贊
正如busybear指出的那樣,循環(huán)不是必需的:您的替換不依賴于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)
添加回答
舉報(bào)