清理不带分割/条带/内置功能的字符串

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)

chr*_*opp 0

我的方法是保留最后一个字符可用,并决定它是否是空格:

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)