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

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个回答

1986

要删除字符串周围的所有空白字符,请使用.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'
注意,str.strip()方法会移除所有空白字符,包括制表符和换行符。如果你只想移除空格,请在strip方法中指定要移除的特定字符作为参数:
>>> "  Hello\n  ".strip(" ")
'Hello\n'

要删除最多只有一个空格:

def strip_one_space(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

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

22
如果你需要strip函数,例如在map函数中使用,你可以通过str.strip()来访问它,就像这样:map(str.strip, collection_of_s)。 - Ward
1
有没有一种方法只修剪末尾的空格? - Nikhil Girraj
2
@killthrush 感谢您提供的参考,但我想您应该指的是 rstrip() 函数。 :-) - Nikhil Girraj
28
有时候我觉得 Python 故意避开被绝大多数编程语言广泛接受且有意义的名称,以便成为“独特”和“不同”的代表——比如 strip 而不是 trimisinstance 而不是 instanceoflist 而不是 array 等等。为什么不使用所有人都熟悉的名称呢?真是的 :P - Gershom Maes
6
strip 的情况下,我完全同意,但是列表与数组完全不同。 - Jacqlyn
显示剩余10条评论

284

如上面的答案所指出的

my_string.strip()

这个函数会移除所有的前导和尾随空白字符, 例如 \n, \r, \t, \f, 空格 .

如果需要更多的灵活性,可以使用以下函数:

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

更多细节请参阅 文档


我相信是 \r\n 而不是 \n\r ... (无法编辑该帖子 - 修改的字符不足) - StefanNch
9
字符的顺序完全不重要。"\n\r" 也会删除 "\r\n"。 - Johannes Overmann

136

strip 不仅限于空格字符:

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

63

以下代码可以移除 myString 字符串中所有的前导和尾随空白:

myString.strip()

31

你需要使用 strip() 函数:

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

for phrase in myphrases:
    print(phrase.strip())

print( [ phrase.strip() for phrase in myphrases ] ) - ingyhere

3

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

import re

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

1
为了消除“空格”在运行Python代码或程序时导致的许多缩进错误。只需按照以下步骤操作;如果Python一直提示错误在第1、2、3、4、5等行的缩进上,只需来回修复该行即可。
然而,如果您仍然遇到与打字错误、运算符等相关的程序问题,请确保您阅读Python为何向您大喊大叫的原因:
首先要检查的是您是否正确缩进。如果是,则检查您的代码中是否混合使用了制表符和空格。
请记住:代码可能看起来很好(对您来说),但解释器拒绝运行它。如果您怀疑这一点,可以将代码带入IDLE编辑窗口,然后选择“编辑...”菜单系统中的“全选”,再选择“格式...”无制表符区域。如果您混合使用了制表符和空格,这将一次性将所有制表符转换为空格(并修复任何缩进问题)。

1

作为初学者,看到这个帖子让我头晕目眩。因此,我想出了一个简单的快捷方式。

虽然 str.strip() 可以去除开头和结尾的空格,但它对字符之间的空格无能为力。

words=input("Enter the word to test")
# If I have a user enter discontinous threads it becomes a problem
# input = "   he llo, ho w are y ou  "
n=words.strip()
print(n)
# output "he llo, ho w are y ou" - only leading & trailing spaces are removed 

所以使用 str.replace() 更合理,更少出错且更直观。以下代码可概括 str.replace() 的使用。

def whitespace(words):
    r=words.replace(' ','') # removes all whitespace
    n=r.replace(',','|') # other uses of replace
    return n
def run():
    words=input("Enter the word to test") # take user input
    m=whitespace(words) #encase the def in run() to imporve usability on various functions
    o=m.count('f') # for testing
    return m,o
print(run())
output- ('hello|howareyou', 0)

在不同的函数中继承相同内容时可能会有帮助。


0
一种方法是使用.strip()方法(删除所有周围的空格)。
str = "  Hello World  "
str = str.strip()
**result: str = "Hello World"**

请注意,.strip() 返回字符串的副本,不会更改原始对象(因为字符串是不可变的)。
如果您希望删除所有空格(而不仅仅是修剪边缘):
str = ' abcd efgh ijk  '
str = str.replace(' ', '')
**result: str = 'abcdefghijk'

0

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

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

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