如何修剪空白? [英] How do I trim whitespace?
问题描述
是否有一个 Python 函数可以修剪字符串中的空格(空格和制表符)?
Is there a Python function that will trim whitespace (spaces and tabs) from a string?
示例:\t 示例字符串\t
→ 示例字符串
推荐答案
对于两边的空格使用 str.strip
:
For whitespace on both sides use str.strip
:
s = " \t a string example\t "
s = s.strip()
对于右侧的空白使用 rstrip
:
For whitespace on the right side use rstrip
:
s = s.rstrip()
对于左侧的空白 lstrip
:
For whitespace on the left side lstrip
:
s = s.lstrip()
正如 thedz 指出的那样,您可以提供一个参数来将任意字符剥离到任何这些函数中,如下所示:
As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:
s = s.strip(' \t\n\r')
这将从左侧、右侧去除任何空格、\t
、\n
或 \r
字符字符串的一侧或两侧.
This will strip any space, \t
, \n
, or \r
characters from the left-hand side, right-hand side, or both sides of the string.
以上示例仅从字符串的左侧和右侧删除字符串.如果您还想从字符串中间删除字符,请尝试 re.sub
:
The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub
:
import re
print(re.sub('[\s+]', '', s))
应该打印出来:
astringexample
这篇关于如何修剪空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!