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。

TA贡献1877条经验 获得超6个赞
当您用空格替换字母时,您的单词会变短。因此len(text)
,如果您删除任何字母,最初的内容将超出范围。但是请注意,replace
正在替换字符串中的所有匹配项,因此甚至不需要循环。
使用循环的另一种方法是在循环过程中跟踪要替换的字母索引,然后在循环完成后进行替换。

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)
添加回答
举报