我如何从Python的字符串去掉空格

How do I trim whitespace from a Python string?

如何从Python中的字符串中删除前导空格和尾随空格?

例如:

1
2
3
4
" Hello" -->"Hello"
" Hello"  -->"Hello"
"Hello"  -->"Hello"
"Bob has a cat" -->"Bob has a cat"


只有一个空间,还是所有这样的空间?如果第二个,那么字符串已经有了.strip()方法:

1
2
3
4
5
6
7
8
>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '          Hello        '.strip()  # ALL spaces at ends removed
'Hello'

但是,如果只需要删除一个空间,可以使用以下方法进行删除:

1
2
3
4
5
6
7
def strip_one_space(s):
    if s.endswith(""): s = s[:-1]
    if s.startswith(""): s = s[1:]
    return s

>>> strip_one_space("   Hello")
'  Hello'

另外,请注意,str.strip()也会删除其他空白字符(例如制表符和换行符)。要只删除空格,可以将要删除的字符指定为strip的参数,即:

1
2
3
4
>>>"  Hello
"
.strip("")
'Hello
'


正如上面的答案所指出的

1
myString.strip()

将删除所有前导和尾随空格字符,如、
、 、f、空格。

要获得更大的灵活性,请使用以下内容

  • 只删除前导空白字符:myString.lstrip()
  • 只删除尾随空格字符:myString.rstrip()
  • 删除特定的空白字符:myString.strip('
    ')
    myString.lstrip('

    ')或myString.rstrip('
    \t')
    等。

文档中提供了更多详细信息


strip也不限于空白字符:

1
2
# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')

这将删除myString中的所有前导和尾随空格:

1
myString.strip()


您想要strip():

1
2
3
4
myphrases = [" Hello"," Hello","Hello","Bob has a cat" ]

for phrase in myphrases:
    print phrase.strip()

我找不到我要找的解决方案,所以我创建了一些自定义函数。你可以试试看。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def cleansed(s: str):
   """:param s: String to be cleansed"""
    assert s is not (None or"")
    # return trimmed(s.replace('"', '').replace("'",""))
    return trimmed(s)


def trimmed(s: str):
   """:param s: String to be cleansed"""
    assert s is not (None or"")
    ss = trim_start_and_end(s).replace('  ', ' ')
    while '  ' in ss:
        ss = ss.replace('  ', ' ')
    return ss


def trim_start_and_end(s: str):
   """:param s: String to be cleansed"""
    assert s is not (None or"")
    return trim_start(trim_end(s))


def trim_start(s: str):
   """:param s: String to be cleansed"""
    assert s is not (None or"")
    chars = []
    for c in s:
        if c is not ' ' or len(chars) > 0:
            chars.append(c)
    return"".join(chars).lower()


def trim_end(s: str):
   """:param s: String to be cleansed"""
    assert s is not (None or"")
    chars = []
    for c in reversed(s):
        if c is not ' ' or len(chars) > 0:
            chars.append(c)
    return"".join(reversed(chars)).lower()


s1 = '  b Beer '
s2 = 'Beer  b    '
s3 = '      Beer  b    '
s4 = '  bread butter    Beer  b    '

cdd = trim_start(s1)
cddd = trim_end(s2)
clean1 = cleansed(s3)
clean2 = cleansed(s4)

print("
Str: {0} Len: {1} Cleansed: {2} Len: {3}"
.format(s1, len(s1), cdd, len(cdd)))
print("
Str: {0} Len: {1} Cleansed: {2} Len: {3}"
.format(s2, len(s2), cddd, len(cddd)))
print("
Str: {0} Len: {1} Cleansed: {2} Len: {3}"
.format(s3, len(s3), clean1, len(clean1)))
print("
Str: {0} Len: {1} Cleansed: {2} Len: {3}"
.format(s4, len(s4), clean2, len(clean2)))


我想删除一个字符串中太多的空格(也在字符串之间,不仅仅是在开头或结尾)。我做了这个,因为我不知道怎么做否则:

1
2
3
4
5
6
7
8
9
10
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)

这将在一个空格中替换双空格,直到不再有双空格为止