Mic*_*icz 5 python string indexing
我的要求
使用Python创建一个函数cleanstring(S)来"清理"句子中的空格S.
这个程序是关于你编写代码来搜索字符串来查找单词,所以你不能在Python中使用split函数.
您可以使用if和while语句的基本功能以及len和concatentation的字符串操作来解决此问题.
例如:如果输入是:"Hello to the world!" 那么输出应该是:"向世界问好!"
题
我的程序删除程序中比需要的更多字符.
输入:"Hello World!"
输出:"HellWorl"
如何修复程序中的错误?
def cleanupstring (S):
newstring = ["", 0]
j = 1
for i in range(len(S) - 1):
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])
Run Code Online (Sandbox Code Playgroud)
我的方法是保留最后一个字符可用,并决定它是否是空格:
def cleanupstring (S):
newstring = ["", 0]
last_character = ' ' # catch initial spaces
for i in range(len(S)-1):
char = S[i]
if char is ' ' and last_character is ' ':
continue # ignore
else:
last_character = char
newstring [0] = newstring[0] + char
return newstring
Run Code Online (Sandbox Code Playgroud)