简体   繁体   English

在Python字符串中删除空格

[英]Removing White Spaces in a Python String

The general question is to remove all extra spaces from a python string so that there is only one space between each word, and no spaces at the beginning or end of the string. 通常的问题是从python字符串中删除所有多余的空格,以便每个单词之间只有一个空格,而字符串的开头或结尾没有空格。

For example, ' Hello to the world ' will return as 'Hello to the world' 例如,“向世界问好”将返回为“向世界问好”

We are not allowed to use the split command, or any commands besides basic string operators (length and concantenation) and if and while commands. 我们不允许使用split命令,也不能使用基本字符串运算符(长度和并发)以及if和while命令以外的任何命令。

I have written my program so that it removes the spaces at the beginning of the string as well as extra spaces between words, however, if I have even one space after the last word in the input string the program returns an error that "index[i] is out of range". 我已经编写了程序,以便删除字符串开头的空格以及单词之间的多余空格,但是,如果我在输入字符串的最后一个单词之后甚至还有一个空格,程序将返回错误“ index [ i]超出范围”。

Here is my program: 这是我的程序:

def cleanstring (s):
    i=0
    while s[i]==' ':
        i=i+1
    s=s[i:len(s)]
    i=0
    while i<len(s):
        if s[i]!=' ':
            i=i+1
        else:
            if i<len(s) and s[i]==' ':
                i=i+1
            if s[i]==' ' and i+1<len(s):
                s=s[0:i]+s[i+1:len(s)]
                i=0
    return(s)

Hopefully someone can help me determine what is wrong with it. 希望有人可以帮助我确定问题所在。 It seems as though I've tried everything but I know that it's just my inexperience with python. 似乎我已经尝试了所有方法,但我知道这只是我对python的经验。

There is actually an easy and clever fix. 实际上有一个简单而聪明的修复方法。 Change 更改

if s[i]==' ' and i+1<len(s):

to... 至...

if i<len(s) and s[i]==' ':

This works because Python short-circuits and if a falsy value is encountered at any point. 这是有效的,因为Python会短路, and在任何时候都遇到伪造的值。 This means that after i<len(s) evaluates to False and Python encounters and , it will immediately move on to the elif or else clauses if there are any. 这意味着在i<len(s)计算为False并且Python遇到and ,它将立即移至elifelse子句(如果有)。 Thus, the second half is never evaluated so there is no IndexError . 因此,后半部分从不评估,因此没有IndexError

Now, this program does not work perfectly. 现在,该程序无法正常运行。 There are other problems with it, but as this is a homework assignment, I am reluctant to offer any more help. 还有其他的问题,但因为这是一个家庭作业,我不愿意提供任何更多的帮助。 Aside from this hint: you need another while loop. 除了这个提示:您还需要另一个while循环。

You need to check your i is in range in one more place. 您需要在另外一个地方检查您的i是否在范围内。 Give this a shot: 试一下:

def cleanstring(s):
    i=0
    while s[i]==' ':
        i=i+1
    s=s[i:len(s)]
    i=0
    while i<len(s):
        if s[i]==' ':
            if (i+1)<len(s) and s[i+1]==' ':
                s=s[0:i]+s[i+1:len(s)]
            else:
                i=i+1
        else:
            i=i+1
    if s[len(s)-1]==' ':
        s=s[0:len(s)-1]
    return(s)

Here is your implementation structure, with the required changes: 这是您的实现结构,并进行了必要的更改:

def cleanstring (s):
    i=0
    while s[i]==' ':
        i=i+1
    s=s[i:len(s)]
    i=0
    while i<len(s):
        if s[i]!=' ':
            i=i+1
        else:
            if i<len(s) and s[i]==' ':
                i=i+1
            if i<len(s) and s[i]==' ':
                s=s[0:i]+s[i+1:len(s)]
                i=0
    if s[-1] == ' ':
        s = s[:-1]
    return(s)

What is changed is: 更改的是:

if s[i]==' ' and i+1<len(s):

To: 至:

if i<len(s) and s[i]==' ':

But this will keep one more space at the end, so 但这将在最后保留一个空间,因此

if s[-1] == ' ':
            s = s[:-1]

Enjoy. 请享用。

This seems to work just fine. 这似乎工作正常。 Check it out. 看看这个。 The repr() just gives the string in quotes, in order to see the actual number of spaces before and after the words. repr()只是将字符串用引号引起来,以便查看单词前后的实际空格数。

def cleanstring (s):
    hit_letter = False
    space_counter = 0
    tmp = list()
    for letter in s:
        if letter.isalpha():
            space_counter = 0
            hit_letter = True
            tmp.append(letter)
            print letter
        elif hit_letter:
            space_counter += 1
            if space_counter < 2:
                tmp.append(letter)
    return ''.join(tmp[:-1])


print repr(cleanstring('  Hi to the  world '))

Using some recursion 使用一些递归

def cleanString(word):
    if word[0]==" ":
        if len(word)>1:
            return cleanString(word[1:])
        return word[1:]
    elif len(word)>1:
        return word[0]+cleanString(word[1:])
    return word
print cleanString("   abcd  ") == "abcd" # True
print cleanString("   abcd  ") # abcd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM