为了账号安全,请及时绑定邮箱和手机立即绑定

字符串索引超出范围问题 - 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 关注
  • 424 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号