从 Python 中的字符串中删除空格
本文向您展示了如何在 Python 中删除字符串中的空格。它可以主要分为两种不同的方法;一种是 Pythonstr
方法,例如str.split()
and str.replace()
;另一种是Python正则表达式方法。
我们将" Demo Example "
在下面的例子中使用该字符串作为要处理的字符串。
在 Python 中删除字符串开头的空格
str.lstrip()
去除开头空格的方法
>>> demo = " Demo Example "
>>> demo.lstrip()
"Demo Example "
此处,str.lstrip()
方法删除方法参数中指定的前导字符。如果没有给出参数,它只是从 Python 字符串中删除前导空格。
Python Regex 方法 –re.sub
去除 Python 字符串中的空格
>>> import re
>>> demo = " Demo Example "
>>> re.sub(r"^\s+", "", demo)
"Demo Example "
^
强制regex只在开头找到匹配的字符串,也\s
就是匹配所有不同种类的空格,比如whitespace、tab、return等等,或者说,等于这些特殊字符的集合[ \t\n\r\f\v]
。+
表示它应该尽可能多地匹配空格。
您可以参考此Python 正则表达式教程以了解有关正则表达式的更多信息。
在 Python 中删除字符串末尾的空格
str.rstrip()
去除 Python 字符串空格的方法
与之相对的是str.lstrip()
去掉字符串开头的字符,str.rstrip()
去掉字符串结尾的字符。
>>> demo = " Demo Example "
>>> demo.lstrip()
" Demo Example"
Python 正则表达式方法 –re.sub
修剪 Python 字符串空格
同样,您应该使用与字符串末尾的空格相匹配的表达式。
>>> import re
>>> demo = " Demo Example "
>>> re.sub(r"\s+$", "", demo)
" Demo Example"
在 Python 中删除字符串开头和结尾的空格
str.strip()
从 Python 字符串中删除空格的方法
str.strip()``str.lstrip()
是和的组合,str.rstrip()
用于删除字符串开头和结尾的空格。
>>> demo = " Demo Example "
>>> demo.strip()
"Demo Example"
Python 正则表达式sub()
方法
>>> import re
>>> demo = " Demo Example "
>>> re.sub(r"^\s+|\s+$", "", demo)
"Demo Example"
从 Python 中的字符串中删除所有空格
Python 字符串替换方法str.replace()
没有必要检查空白的位置。因此,您可以使用str.replace()
方法将所有空格替换为空字符串。
>>> demo = " Demo Example "
>>> demo.replace(" ", "")
'DemoExample'
Python字符串正则表达式替换sub()
方法
正则表达式只能\s+
匹配空格。
>>> import re
>>> demo = " Demo Example "
>>> re.sub(r"\s+", "", demo)
"DemoExample"
仅删除 Python 中字符串的重复空格
Python 字符串拆分方法str.split()
>>> demo = " Demo Example "
>>> " ".join(demo.split())
'Demo Example'
str.split()
返回字符串中子字符串的列表,使用空格作为分隔符字符串。
Python正则表达式拆分方法re.split()
>>> import re
>>> demo = " Demo Example "
>>> " ".join(re.split(r"\s+", demo)
" Demo Example "
警告
re.split()
如果字符串在这些位置有空格,则 和 的结果str.split()
不同 wherere.split()
将在列表的开头或结尾有一个空字符串,但str.split()
在其结果中不包含任何空字符串。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。