【发布时间】: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]。 -
如果您要询问您的程序产生的错误,与我们分享错误和回溯总是一个好主意。我们不能越过你的肩膀看到你的屏幕。