迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中将文件或字符串中的制表符替换为空格

作者:迹忆客 最近更新:2023/01/26 浏览次数:

使用 str.replace() 方法用空格替换制表符,例如 result = my_str.replace('\t', ' ')str.replace() 方法将返回一个新字符串,其中每个出现的制表符都替换为空格。

my_str = 'one\ttwo\tthree'

# ✅ 将字符串中的空格替换制表符

result = my_str.replace('\t', ' ')
print(repr(result))  # 👉️ 'one two three'

# -----------------------------------------

# ✅ 将文件中的空格替换制表符

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', ' '))

# -----------------------------------------

# ✅ 将字符串列表中的空格替换制表符
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 字符串中我们要替换的子串
  • new 替换每次出现的 old
  • count 仅替换第一个 count 出现(可选)

该方法不会更改原始字符串。 字符串在 Python 中是不可变的。

要用文件中的空格替换制表符:

  1. 以读取模式打开文件并读取其内容。
  2. 以写入模式打开文件。
  3. 使用 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 语句自动为我们关闭文件。


用字符串列表中的空格替换制表符

要用列表中的空格替换制表符:

  1. 使用列表理解来遍历列表。
  2. 使用 str.replace() 方法将每个项目的制表符替换为空格。
  3. 新列表中的项目将包含空格而不是制表符。
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() 方法将当前项目中的制表符替换为空格。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便