在 Python 中用文件或字符串中的空格替换制表符
Replace tabs with spaces in a File or String in Python
使用该str.replace()
方法将制表符替换为空格,例如
result = my_str.replace('\t', ' ')
. 该str.replace()
方法将返回一个新字符串,其中每个出现的制表符都替换为空格。
主程序
my_str = 'one\ttwo\tthree' # ✅ Replace tabs with spaces in a string result = my_str.replace('\t', ' ') print(repr(result)) # 👉️ 'one two three' # ----------------------------------------- # ✅ Replace tabs with spaces in a file with open('example.txt', 'r', encoding='utf-8') as input_file: lines = input_file.readlines() print(lines) with open('example.txt', 'w', encoding='utf-8') as output_file: for line in lines: output_file.write(line.replace('\t', ' ')) # ----------------------------------------- # ✅ Replace tabs with spaces in list of strings my_list = ['a\tb', 'c\td', 'e\tf'] new_list = [item.replace('\t', ' ') for item in my_list] print(new_list) # 👉️ ['a b', 'c d', 'e f']
我们使用了str.replace()
将制表符替换为空格的方法。
第一个示例使用该方法将字符串中的制表符替换为空格。
主程序
my_str = 'one\ttwo\tthree' result = my_str.replace('\t', ' ') print(repr(result)) # 👉️ 'one two three'
str.replace方法返回字符串
的副本,其中所有出现的子字符串都被提供的替换项替换。
该方法采用以下参数:
姓名 | 描述 |
---|---|
老的 | 字符串中我们要替换的子串 |
新的 | 每次出现的替换old |
数数 | 只count 替换第一次出现的(可选) |
该方法不会更改原始字符串。字符串在 Python 中是不可变的。
要用文件中的空格替换制表符:
- 以读取模式打开文件并读取其内容。
- 以写入模式打开文件。
- 使用该
str.replace()
方法将每一行的制表符替换为空格。
主程序
with open('example.txt', 'r', encoding='utf-8') as input_file: lines = input_file.readlines() print(lines) with open('example.txt', 'w', encoding='utf-8') as output_file: for line in lines: output_file.write(line.replace('\t', ' '))
确保更新文件的名称。
我们遍历文件中的行,并使用该
str.replace()
方法将每行的制表符替换为空格。该with
语句会自动为我们关闭文件。
用字符串列表中的空格替换制表符#
要用列表中的空格替换制表符:
- 使用列表理解来遍历列表。
- 使用该
str.replace()
方法将每个项目的制表符替换为空格。 - 新列表中的项目将包含空格而不是制表符。
主程序
my_list = ['a\tb', 'c\td', 'e\tf'] new_list = [item.replace('\t', ' ') for item in my_list] print(new_list) # 👉️ ['a b', 'c d', 'e f']
我们使用列表理解来迭代列表。
列表推导用于对每个元素执行某些操作或选择满足条件的元素子集。
在每次迭代中,我们使用该str.replace()
方法将当前项目中的制表符替换为空格。