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

使用Regex将文件转为Base64并替换字符串时遇TypeError求助

解决Base64编码内容替换字符串时的TypeError问题

错误原因

base64.b64encode()返回的是bytes类型对象,而re.sub()的替换值参数要求必须是字符串类型,类型不匹配直接触发了TypeError。

修正方案

将Base64编码得到的bytes对象解码为UTF-8格式的字符串即可,使用decode('utf-8')方法完成转换。

完整修正代码

import re
import base64

file = "test.txt"
with open(file, "r") as f:
    # 读取文件内容→转bytes→Base64编码→解码为字符串
    encoded_file = base64.b64encode(f.read().encode("utf-8")).decode("utf-8")

string = "string"
pattern = "pattern"
updt_str = re.sub(pattern, encoded_file, string)

关键步骤说明

  • f.read().encode("utf-8"):把文件读取的字符串转为bytes格式,满足Base64编码的输入要求
  • base64.b64encode(...).decode("utf-8"):将Base64编码后的bytes对象转换为字符串,适配re.sub()的参数类型要求

内容的提问来源于stack exchange,提问作者Antonio Costa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:25:26