【问题标题】:String out of index字符串超出索引
【发布时间】:2017-11-20 03:40:16
【问题描述】:

我的要求

使用 Python 创建函数 cleanstring(S) 以“清理”句子 S 中的空格。

  • 句子的前面和/或结尾和/或单词之间可能有额外的空格。
  • 子例程返回没有多余空格的句子的新版本。
    • 也就是说,在新的字符串中,单词应该相同,但开头不能有空格,每个单词之间只有一个空格,结尾不能有空格。

这个程序是关于你编写代码来搜索字符串以查找单词,因此你不能在 Python 中使用 split 函数。

你可以通过 if 和 while 语句的基本功能以及 len 和 concatenation 的字符串操作来解决这个问题。

例如:如果输入是:“Hello to the world !”那么输出应该是:“Hello to the world!”

问题

我的程序出错了。

如何修复程序中的错误?

def cleanupstring (S):
newstring = ["", 0]
j = 1
for i in range(len(S)):
    if S[i] != " " and S[i+1] != " ":
        newstring[0] = newstring[0] + S[i]
    else:
        newstring[1] = newstring [1] + 1

return newstring


# main program

sentence = input("Enter a string: ")

outputList = cleanupstring(sentence)

print("A total of", outputList[1], "characters have been removed from your 
string.")
print("The new string is:", outputList[0]) 

【问题讨论】:

  • 为您的问题尝试正则表达式
  • 试试for i in range(len(S) -1):。在and S[i+1] != " ": 中,您正在尝试访问i+1 索引...好吧,当您到达该循环的最后时,i+1 超出了列表的末尾。
  • 最后一个字符没有S[i+1]
  • 如果您要询问您的程序产生的错误,与我们分享错误和回溯总是一个好主意。我们不能越过你的肩膀看到你的屏幕。

标签: python string indexing


【解决方案1】:

可以使用不同的方法来删除前导和尾随空格,将多个空格转换为一个,以及删除感叹号、逗号等之前的空格:

mystr = "  Hello  .       To  ,   the world !  "
print(mystr)

mystr = mystr.strip()               # remove leading and trailing spaces

import re                           # regex module
mystr = re.sub(r'\s+'," ", mystr)   # convert multiple spaces to one space.
mystr = re.sub(r'\s*([,.!])',"\\1", mystr)  # remove spaces before comma, period and exclamation etc.
print(mystr)

输出:

  Hello  .       To  ,   the world !  
Hello. To, the world!

【讨论】:

    【解决方案2】:

    评论中的解决方案是正确的。您遇到错误是因为您尝试在循环 for i in range(len(S)):

    中访问 S[i+1]

    解决方案

    只循环到倒数第二个元素

    for i in range(len(S) - 1):
    

    建议

    正如你所说,你不能使用 spit() 函数,所以假设你可以使用其他函数(修改字符串,而不是提取单词),strip() 函数和一点正则表达式将完成您的 cleanupstring() 正在尝试做的事情。

    代码

    def cleanupstring (S):
        newstring = ["", 0]
        init_length = len(S)
        S = S.strip()    #remove space from front and end
        S = re.sub(r'\s+'," ", S)   #remove extra space from between words
        newstring[0] = S
        newstring[1] = init_length - len(S)
        return newstring
    
    # main program
    sentence = input("Enter a string: ")
    outputList = cleanupstring(sentence)
    
    print("A total of", outputList[1], "characters have been removed from your 
    string.")
    print("The new string is:", outputList[0]) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 1970-01-01
      • 2010-10-31
      • 2016-02-19
      • 2012-03-02
      • 2016-02-10
      相关资源
      最近更新 更多