介绍
本教程提供了在Python中从字符串中删除空白的各种方法的示例。
A Python String is immutable, so you can’t change its value. Any method that manipulates a string value returns a new string.
使用DigitalOcean App Platform从GitHub部署您的Python应用程序。让DigitalOcean专注于扩展您的应用。
本教程中的示例使用Python交互式控制台在命令行中演示不同的去除空格的方法。示例中使用了以下字符串:
s = ' Hello World From DigitalOcean \t\n\r\tHi There '
输出是:
Output Hello World From DigitalOcean
Hi There
此字符串包含不同类型的空白和换行字符,如空格(
)、制表符(\t
)、换行符(\n
)和回车符(\r
)。
使用strip()
方法去除首尾空格
Python字符串strip()
方法从字符串中删除首尾字符。默认要删除的字符是空格。
声明字符串变量:
- s = ' Hello World From DigitalOcean \t\n\r\tHi There '
使用strip()
方法去除字符串的前导和尾随空格:
- s.strip()
输出为:
Output'Hello World From DigitalOcean \t\n\r\tHi There'
如果你只想去掉前导空格或尾随空格,那么你可以使用lstrip()
和rstrip()
方法。
使用replace()
方法移除所有空格
你可以使用replace()
方法从字符串中移除所有空白字符,包括单词之间的空格。
声明字符串变量:
- s = ' Hello World From DigitalOcean \t\n\r\tHi There '
使用replace()
方法将空格替换为空字符串:
- s.replace(" ", "")
输出为:
Output'HelloWorldFromDigitalOcean\t\n\r\tHiThere'
使用join()
和split()
方法移除重复的空格和换行符
您可以使用join()
方法与split()
方法去除所有重复的空格和换行字符。在这个例子中,split()
方法将字符串拆分成一个列表,使用任何空格字符作为默认分隔符。然后,join()
方法将列表重新连接成一个字符串,每个单词之间用单个空格" "
分隔。
声明字符串变量:
- s = ' Hello World From DigitalOcean \t\n\r\tHi There '
使用join()
和split()
方法一起去除重复的空格和换行字符:
- " ".join(s.split())
输出为:
Output'Hello World From DigitalOcean Hi There'
使用translate()
方法去除所有空格和换行字符
您可以使用translate()
方法去除所有空格和换行字符。translate()
方法用字典或映射表中定义的字符替换指定的字符。以下示例使用了一个自定义字典,其中包含了string.whitespace
字符串常量,该常量包含了所有的空格字符。自定义字典{ord(c): None for c in string.whitespace}
将string.whitespace
中的所有字符替换为None
。
导入string
模块以便您可以使用string.whitespace
:
- import string
声明字符串变量:
- s = ' Hello World From DigitalOcean \t\n\r\tHi There '
使用translate()
方法去除所有空白字符:
- s.translate({ord(c): None for c in string.whitespace})
输出为:
Output'HelloWorldFromDigitalOceanHiThere'
使用正则表达式去除空白字符
你也可以使用正则表达式匹配空白字符,并使用re.sub()
函数去除它们。
这个示例使用文件regexspaces.py
,展示了一些你可以使用正则表达式去除空白字符的方法:
import re
s = ' Hello World From DigitalOcean \t\n\r\tHi There '
print('Remove all spaces using regex:\n', re.sub(r"\s+", "", s), sep='') # \s 匹配所有空白字符
print('Remove leading spaces using regex:\n', re.sub(r"^\s+", "", s), sep='') # ^ 匹配字符串开始
print('Remove trailing spaces using regex:\n', re.sub(r"\s+$", "", s), sep='') # $ 匹配字符串结束
print('Remove leading and trailing spaces using regex:\n', re.sub(r"^\s+|\s+$", "", s), sep='') # | 表示或条件
从命令行运行该文件:
python3 regexspaces.py
你将得到以下输出:
Remove all spaces using regex:
HelloWorldFromDigitalOceanHiThere
Remove leading spaces using regex:
Hello World From DigitalOcean
Hi There
Remove trailing spaces using regex:
Hello World From DigitalOcean
Hi There
Remove leading and trailing spaces using regex:
Hello World From DigitalOcean
Hi There
结论
在本教程中,你学到了一些在Python中从字符串中去除空白字符的方法。继续学习有关Python字符串的知识。
Source:
https://www.digitalocean.com/community/tutorials/python-remove-spaces-from-string