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

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

当前回答

我无法找到我正在寻找的解决方案,所以我创建了一些自定义函数。你可以试试。

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)))

其他回答

我无法找到我正在寻找的解决方案,所以我创建了一些自定义函数。你可以试试。

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)))

Strip也不局限于空白字符:

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

在Pyhton中运行完成的代码或程序时,为了删除会导致大量缩进错误的“空白”。只需执行以下操作;显然,如果Python一直告诉我们错误是第1、2、3、4、5行中的缩进,等等……把那条线来回固定。

然而,如果你仍然遇到与输入错误、操作符等相关的程序问题,请确保你阅读了错误Python为什么对你大喊大叫:

首先要检查的是你是否有 缩进。如果你有,那么检查一下你是否有 在代码中混合制表符和空格。

记住:代码 将看起来很好(对您),但解释器拒绝运行它。如果 如果你怀疑这一点,一个快速的解决方法就是把你的代码带入 IDLE编辑窗口,然后选择编辑…“从 菜单系统,在选择格式之前…“Untabify地区。 如果你混合了制表符和空格,这将转换你所有的 制表符到空格一次性完成(并修复任何缩进问题)。

这也可以用正则表达式来实现

import re

input  = " Hello "
output = re.sub(r'^\s+|\s+$', '', input)
# output = 'Hello'

正如上面的答案所指出的

my_string.strip()

将删除所有前导和后面的空白字符,如\n, \r, \t, \f,空格。

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

只删除前导空白字符: 只移除尾随的空格字符: 删除特定的空白字符:my_string.strip('\n')或my_string.lstrip('\n\r')或my_string.rstrip('\n\t')等。

更多细节可以在文档中找到。