如何从字符串中去除空格?

1361

如何在Python中删除字符串开头和结尾的空格?

" Hello world " --> "Hello world"
" Hello world"  --> "Hello world"
"Hello world "  --> "Hello world"
"Hello world"   --> "Hello world"

1
只是想让更多的人了解 rstrip 的陷阱。'WKHS.US.TXT'.rstrip('.US.TXT') 将返回 WKH 而不是 WKHS。这个 rstrip 会产生一个难以排查的 BUG。 - huang
1
同意。rstrip的参数是一个字符列表,应该从字符串末尾剥离。因此,“WKHS”具有后缀“S”,这也是我们要求rstrip删除的字符。之后,出现了“H”。它将是不属于参数的字符。剥离会在无法剥离疑问字符时立即停止。 - Prabhu U
只需执行 .split('.')[0] 即可 - Coder
13个回答

0
如何在Python中从字符串中删除前导和尾随空格?
因此,下面的解决方案将删除前导和尾随空格以及中间空格。例如,如果您需要获取一个清晰的字符串值而不带有多个空格。
>>> str_1 = '     Hello World'
>>> print(' '.join(str_1.split()))
Hello World
>>>
>>>
>>> str_2 = '     Hello      World'
>>> print(' '.join(str_2.split()))
Hello World
>>>
>>>
>>> str_3 = 'Hello World     '
>>> print(' '.join(str_3.split()))
Hello World
>>>
>>>
>>> str_4 = 'Hello      World     '
>>> print(' '.join(str_4.split()))
Hello World
>>>
>>>
>>> str_5 = '     Hello World     '
>>> print(' '.join(str_5.split()))
Hello World
>>>
>>>
>>> str_6 = '     Hello      World     '
>>> print(' '.join(str_6.split()))
Hello World
>>>
>>>
>>> str_7 = 'Hello World'
>>> print(' '.join(str_7.split()))
Hello World

正如您所看到的,这将删除字符串中的所有多余空格(对于所有输出来说,结果都是Hello World)。位置并不重要。但是如果您真的需要前导和尾随空格,则可以使用 strip() 方法。


0
如果您想要从左右两侧裁剪固定数量的空格,可以这样做:
def remove_outer_spaces(text, num_of_leading, num_of_trailing):
    text = list(text)
    for i in range(num_of_leading):
        if text[i] == " ":
            text[i] = ""
        else:
            break

    for i in range(1, num_of_trailing+1):
        if text[-i] == " ":
            text[-i] = ""
        else:
            break
    return ''.join(text)

txt1 = "   MY name is     "
print(remove_outer_spaces(txt1, 1, 1))  # result is: "  MY name is    "
print(remove_outer_spaces(txt1, 2, 3))  # result is: " MY name is  "
print(remove_outer_spaces(txt1, 6, 8))  # result is: "MY name is"

-1

我想要移除字符串中过多的空格(不仅限于开头或结尾,还包括字符串中间的空格)。我写了这个代码,因为我不知道其他方法:

string = "Name : David         Account: 1234             Another thing: something  " 

ready = False
while ready == False:
    pos = string.find("  ")
    if pos != -1:
       string = string.replace("  "," ")
    else:
       ready = True
print(string)

这个函数将连续的双空格替换为单空格,直到没有双空格为止。


虽然这个方法可以工作,但并不是很高效,请使用这个方法代替:https://dev59.com/LnI95IYBdhLWcg3w8y6N#2077906 - Arklur
如果你想删除所有空格,只需使用string.replace(" ",""),不需要使用这些代码。 - Mohamed Fathallah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接