字符串索引超出范围问题-Python

时间:2019-01-13 03:36:48

标签: python string

我正在尝试制作一个有损文本压缩程序,该程序将从输入中删除所有元音,除非元音是单词的第一个字母。我在第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 个答案:

答案 0 :(得分:0)

用空格替换字母时,单词会变短。因此,如果您删除任何字母,最初的import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="test") grid = Gtk.Grid() self.add(grid) button1 = Gtk.Button(label="Button 1", expand = True) button2 = Gtk.Button(label="Button 2", expand = True) button3 = Gtk.Button(label="Button 3", expand = True) button4 = Gtk.Button(label="Button 4", expand = True) button5 = Gtk.Button(label="Button 5", expand = True) button6 = Gtk.Button(label="Button 6", expand = True) grid.add(button1) grid.attach(button2, 1, 0, 2, 1) grid.attach_next_to(button3, button1, Gtk.PositionType.BOTTOM, 1, 2) grid.attach_next_to(button4, button3, Gtk.PositionType.RIGHT, 2, 1) grid.attach(button5, 1, 2, 1, 1) grid.attach_next_to(button6, button5, Gtk.PositionType.RIGHT, 1, 1) win = MainWindow() win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main() 将会超出范围。不过请注意,len(text)会替换字符串中的所有匹配项,因此甚至不需要循环。

使用循环的另一种方法是只跟踪循环中要替换的字母索引,然后在循环完成后替换。

答案 1 :(得分:0)

通过用“”替换任何字符来缩短字符串长度,这意味着如果删除一个字符,则迭代器中使用的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。

答案 2 :(得分:0)

正如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)