Python 打印/写入包含 "\f"的字符串

标签 python string

我正在尝试读取一个文件并将每个“a ... a”替换为“\footnotemark”

with open('myfile', 'r') as myfile:
   data = myfile.read()
   data = re.sub('<a.+?</a>', '\footnotemark', data)

Python 总是以某种方式将 '\footnotemark' 转换为 '\x0cootnotemark'('\f' 转换为 '\x0c')。到目前为止我试过了

  • 转义:'{2 Backslashes}footnotemark'
  • 原始字符串:r'\footnotemark' 或 r'"\footnotemark"'

这些都不起作用

示例输入:

foo<a href="anything">asdasd</a> bar

示例输出:

foo\footnotemark bar

最佳答案

假设是 Python2,因为你没有提到任何关于版本的事情

#/usr/bin/python

import re

# myfile is saved with utf-8 encoding
with open('myfile', 'r') as myfile:

    text = myfile.read()
    print text
    data = re.sub('<a.+?</a>', r'\\footnotemark', text)

print data

输出

foo<a href="anything">asdasd</a> bar
foo\footnotemark bar

关于Python 打印/写入包含 "\f"的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35313999/

相关文章:

java - WordTo2DChar ,除了函数索引之外不要使用任何其他字符串函数

string - 通过替换获取字符串的回文

python - 将字符串中的每个字符转换为字典键

Python 线程支持脚本的其余部分

python - 如何从新闻摘要中提取股票代码NUMBER?

python - 如何使用 lxml、XPath 和 Python 从网页中提取链接?

Python:确定固定长度列的通用算法

json - 如何用 jq (或其他替代方法)解析 JSON 字符串?

python - Plotly Dash 应用程序未运行

python - 关于如何创建 Pandas DataFrame 的困惑