在 Python 中用单个空格替换多个空格

目录

Replace multiple spaces with a single space in Python

  1. 在 Python 中用单个空格替换多个空格
  2. 使用 re.sub() 将多个空格替换为单个空格
  3. 用 Python 文件中的单个空格替换多个空格

在 Python 中用单个空格替换多个空格

用一个空格替换多个空格:

  1. 使用该str.split()方法在每个空白字符上拆分字符串。
  2. 使用该str.join()方法用空格连接字符串列表。
  3. 新字符串中的单词将由一个空格分隔。
主程序
my_str = 'bobby hadz com' # ✅ replace multiple whitespace characters with single space result = " ".join(my_str.split()) print(repr(result)) # 👉️ 'bobby hadz com'

该示例使用str.split()str.join()方法将多个空白字符替换为一个空格。

str.split ()方法使用定界符将字符串拆分为子字符串列表。

当在没有分隔符的情况下调用该str.split()方法时,它将连续的空白字符视为单个分隔符。
主程序
my_str = 'bobby hadz com' # 👇️ ['bobby', 'hadz', 'com'] print(my_str.split())

当不带参数调用时,该str.split()方法将拆分为连续的空白字符(例如\t,\n等),而不仅仅是空格。

下一步是使用该str.join()方法连接带有空格分隔符的字符串列表。

主程序
my_str = 'bobby hadz com' result = " ".join(my_str.split()) print(repr(result)) # 👉️ 'bobby hadz com' # 👇️ bobby hadz com print(' '.join(['bobby', 'hadz', 'com']))

str.join方法将一个可迭代对象作为参数并返回一个字符串,该字符串是可迭代对象中字符串的串联

调用该方法的字符串用作元素之间的分隔符。

使用单个空格替换多个空格re.sub()

另一种方法是使用re.sub()方法。

re.sub方法将返回一个新字符串,该字符串是通过将所有出现的多个空格替换为一个空格而获得的。

主程序
import re my_str = 'bobby hadz com' # 👇️ only covers spaces result = re.sub(' +', ' ', my_str) print(repr(result)) # 👉️ 'bobby hadz com'

如果您需要用一个空格替换多个空白字符,请改用以下代码示例。

主程序
import re my_str = 'bobby hadz com' # 👇️ covers spaces, tabs and newline chars result = re.sub(r'\s+', ' ', my_str) print(repr(result)) # 👉️ 'bobby hadz com'

re.sub方法返回一个新字符串该字符串是通过用提供的替换替换模式的出现而获得的。

如果未找到模式,则按原样返回字符串。

我们传递给该方法的第一个参数re.sub是一个正则表达式。

在我们的正则表达式中,我们有一个空格和一个加号+

主程序
result = re.sub(' +', ' ', my_str)
加号+用于匹配前面的字符(空格)1 次或多次。

In its entirety, the example replaces 1 or more consecutive spaces with a single
space.

Note that the re.sub() method returns a new string, it doesn’t mutate the
original string as strings are immutable in Python.

If you need to replace all whitespace characters with a single space, use the
\s special character instead.

main.py
import re my_str = 'bobby hadz com' result = re.sub(r'\s+', ' ', my_str) print(repr(result)) # 👉️ 'bobby hadz com'

The \s character matches Unicode whitespace characters like [ \t\n\r\f\v].

If your string has trailing whitespace, you might have to use the str.strip()
method to remove it before calling re.sub().

main.py
import re my_str = 'bobby hadz com ' result = re.sub(r'\s+', ' ', my_str.strip()) print(repr(result)) # 👉️ 'bobby hadz com'

The str.strip method returns a copy of
the string with the leading and trailing whitespace removed.

# Replace multiple spaces with a single space in a file in Python

To replace multiple spaces with a single space in a file:

  1. Open the first file in reading mode.
  2. Open the second file in writing mode.
  3. Use the split() and join() methods to replace multiple spaces with a
    single space.
main.py
with open('file-1.txt', 'r', encoding='utf-8') as old_file: lines = old_file.readlines() with open('file-2.txt', 'w', encoding='utf-8') as new_file: for line in lines: new_file.write(' '.join(line.split()) + '\n')

The code sample assumes that you have a file named file-1.txt located in the
same directory as your Python script.

file-1.txt
bobby hadz com one two three

We opened the first file in r (reading) mode and read its lines.

Then, we opened the second file in w (writing) mode and used a
for loop to iterate over the lines of the
first file.

On each iteration, we replace multiple spaces with a single space and write the
result to the second file.

The contents of file-2.txt look as follows.

file-2.txt
bobby hadz com one two three

# Additional Resources

您可以通过查看以下教程来了解有关相关主题的更多信息: