如何修剪字符串中的空格?

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

例如:

" Hello " --> "Hello"
" Hello"  --> "Hello"
"Hello "  --> "Hello"
"Bob has a cat" --> "Bob has a cat"

答案

只是一个空格,还是所有连续的空格?如果是第二个字符串,则字符串已经具有.strip()方法:

>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '   Hello   '.strip()  # ALL consecutive spaces at both ends removed
'Hello'

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

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的参数,即:

>>> "  Hello\n".strip(" ")
'Hello\n'

正如以上答案中指出的

myString.strip()

将删除所有前导和尾随空格字符,例如 \ n,\ r,\ t,\ f,空格。

为了获得更大的灵活性,请使用以下命令

  • 仅删除前导空格字符: myString.lstrip()
  • 仅删除尾随空白字符: myString.rstrip()
  • 删除特定的空白字符: myString.strip('\n')myString.lstrip('\n\r')myString.rstrip('\n\t') ,依此类推。

更多详细信息可在文档中找到

strip不限于空白字符:

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

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

myString.strip()

您要 strip():

myphrases = [ " Hello ", " Hello", "Hello ", "Bob has a cat" ]

for phrase in myphrases:
    print phrase.strip()

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

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)

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

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

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("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s1, len(s1), cdd, len(cdd)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s2, len(s2), cddd, len(cddd)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s3, len(s3), clean1, len(clean1)))
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s4, len(s4), clean2, len(clean2)))

如果要从 left 和 right 修剪指定数量的空格 ,可以执行以下操作:

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"