You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用re.sub移除文本文件制表符(\t)无效的问题求助

问题原因与解决方案

你的代码中,文件里的\t是字面意义的反斜杠加字母t,而非真正的制表符,这就是为什么用re.sub('\t', '', s1)无法移除它们的原因。

在代码的多行字符串s中,Python会把\t解析为制表符(ASCII控制字符),所以替换能生效;但从文件读取时,\t是两个独立字符:\和t,你的正则表达式找的是制表符,自然匹配不到。

修复方法

直接匹配字面的\t序列即可,有两种简单方式:

方式1:使用字符串替换(无需正则)

字符串的replace方法更直接高效:

new_string = s1.replace('\\t', '')

方式2:使用正则匹配

正则中需要用双反斜杠转义反斜杠,或者用原始字符串:

new_string = re.sub(r'\\t', '', s1)

修正后的完整代码

import re
from pathlib import Path

s = """
{
  device_id: '2ysr9t',
  message: '[44,"139076297","xyz",{\n' +
    '\t"connectorId":\t1,\n' +
    '\t"transactionId":\t654954,\n' +
    '\t"Value":\t[{\n' +
    '\t\t\t"timestamp":\t"2023-11-23T00:21:25Z",\n' +
    '\t\t\t"Value":\t[{\n' +
    '\t\t\t\t\t"value":\t"86237168.0",\n' +
    '\t\t\t\t\t"context":\t"Periodic",\n' +
    '\t\t\t\t\t"format":\t"Raw",\n' +
    }"""

data_folder = Path("2ysr9t.txt")

with open(data_folder, 'r', encoding="utf8") as input_file:
    s1 = input_file.read()
    # 使用字符串替换更简单
    new_string = s1.replace('\\t', '')
    print(new_string)

new_string1 = re.sub('\t','',s)
print(new_string1)

内容的提问来源于stack exchange,提问作者Prashant Mani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:40:18