如何在 Python 中刪除字串中的空格

介紹

本教程提供了在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應用平台從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()方法從字符串中刪除前導和尾隨字符。要刪除的默認字符是空格。

聲明字符串變量:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

使用strip()方法來刪除開頭和結尾的空格:

  1. s.strip()

輸出結果是:

Output
'Hello World From DigitalOcean \t\n\r\tHi There'

如果您只想刪除開頭空格或結尾空格,那麼可以使用lstrip()rstrip()方法。

使用replace()方法刪除所有空格

您可以使用replace()方法從字符串中刪除所有空格字符,包括單詞之間的空格。

聲明字符串變量:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

使用replace()方法將空格替換為空字符串:

  1. s.replace(" ", "")

輸出結果是:

Output
'HelloWorldFromDigitalOcean\t\n\r\tHiThere'

使用join()split()方法刪除重複空格和換行字符

您可以使用join()方法与split()方法删除所有重复的空格和换行字符。在这个例子中,split()方法将字符串拆分为一个列表,使用任何空白字符作为默认分隔符。然后,join()方法将列表连接回一个字符串,每个单词之间用一个单空格(" ")隔开。

声明字符串变量:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

使用join()split()方法一起去除重复的空格和换行字符:

  1. " ".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

  1. import string

声明字符串变量:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

使用translate()方法去除所有空格字符:

  1. s.translate({ord(c): None for c in string.whitespace})

输出结果为:

Output
'HelloWorldFromDigitalOceanHiThere'

使用正则表达式去除空格字符

你还可以使用正则表达式匹配空格字符,并使用re.sub()函数将其移除。

以下示例使用文件regexspaces.py演示了一些使用正则表达式去除空格字符的方法:

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='')  # |表示OR条件

从命令行运行该文件:

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