我想消除字符串的所有空白,在两端和单词之间。
我有这样的Python代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
但这只是消除了字符串两侧的空白。如何删除所有空白?
我想消除字符串的所有空白,在两端和单词之间。
我有这样的Python代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
但这只是消除了字符串两侧的空白。如何删除所有空白?
当前回答
消除字符串两端和单词之间的所有空白。
>>> import re
>>> re.sub("\s+", # one or more repetition of whitespace
'', # replace with empty string (->remove)
''' hello
... apple
... ''')
'helloapple'
https://en.wikipedia.org/wiki/Whitespace_character
Python文档:
https://docs.python.org/library/stdtypes.html#textseq https://docs.python.org/library/stdtypes.html#str.replace https://docs.python.org/library/string.html#string.replace https://docs.python.org/library/re.html#re.sub https://docs.python.org/library/re.html#regular-expression-syntax
其他回答
试试这个. .比起使用re,我认为使用split和strip会更好
def my_handle(self):
sentence = ' hello apple '
' '.join(x.strip() for x in sentence.split())
#hello apple
''.join(x.strip() for x in sentence.split())
#helloapple
我发现这个方法最适合我:
test_string = ' test a s test '
string_list = [s.strip() for s in str(test_string).split()]
final_string = ' '.join(string_array)
# final_string: 'test a s test'
它删除了任何空白,制表符等。
小心:
Strip执行rstrip和lstrip(删除开头和结尾空格、制表符、返回值和表单提要,但不删除字符串中间的空格)。
如果你只替换空格和制表符,你最终会得到隐藏的crlf,它们看起来与你正在寻找的内容相匹配,但并不相同。
我使用split()忽略所有空白,使用join()连接 字符串。
sentence = ''.join(' hello apple '.split())
print(sentence) #=> 'helloapple'
我更喜欢这种方法,因为它只是一个表达式(不是一个语句)。 它易于使用,并且无需绑定到变量即可使用。
print(''.join(' hello apple '.split())) # no need to binding to a variable
消除字符串两端和单词之间的所有空白。
>>> import re
>>> re.sub("\s+", # one or more repetition of whitespace
'', # replace with empty string (->remove)
''' hello
... apple
... ''')
'helloapple'
https://en.wikipedia.org/wiki/Whitespace_character
Python文档:
https://docs.python.org/library/stdtypes.html#textseq https://docs.python.org/library/stdtypes.html#str.replace https://docs.python.org/library/string.html#string.replace https://docs.python.org/library/re.html#re.sub https://docs.python.org/library/re.html#regular-expression-syntax