V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
vicker
V2EX  ›  Python

关于 python2 字符串变量转义的问题,求教

  •  
  •   vicker · 2017-08-23 17:12:12 +08:00 · 1673 次点击
    这是一个创建于 2440 天前的主题,其中的信息可能已经有所发展或是发生改变。

    各位大牛好,有个问题一直很困惑,求指点!!! 假设我现在有一字符串如下

    input[0]: print '\xd2\xbb'

    output[0]: һ

    直接输出这个字符串,会出现 h 形状的符号,这是我预期的输出

    现在我将 '\xd2\xbb' 写入文件中, file.txt

    \xd2\xbb
    

    当我读取 file.txt 时,

    with open('file.txt') as f:
        tmp = f.read()
    print tmp
    

    output[1]: \xd2\xbb

    可以看到,python2 在读取文件的时候,将\ 进行了 转义变成了\ 进行输出,并没有直接输出 h 形状的符号 问题:怎么能让让 python2 直接将读取的字符串不通过转义输出呢? 求各位大牛指点,需求是我需要保留文件中这个 h 符号放到函数中进行调用。

    4 条回复    2017-08-28 09:47:40 +08:00
    Patrick95
        1
    Patrick95  
       2017-08-23 18:25:08 +08:00
    为什么不直接把 h 符号写入文件呢?

    https://gist.github.com/FaithPatrick/1186d5c24695ce2bc738e8331f147123
    jingniao
        2
    jingniao  
       2017-08-23 18:56:28 +08:00 via Android
    python 中 str 类型,字面 ‘\xd2\xbb'发生了转义,实际上内存中存储的可以看作 2 个 8 位无符号整形,这个字符串长度在 python2 中是 2
    你写到文件里的\xd2\xbb 是 8 个字符,字符串长度为 8 ……
    vicker
        3
    vicker  
    OP
       2017-08-28 09:46:08 +08:00
    @Patrick95 感谢帮助~~ 当时从文件中获取出来的是\xd2\xbb 这种格式,所以比较纠结,不过后来解决是通过,打开文件的编码格式, codecs.open('file.txt', 'r', encoding='string_escape'),这样引用出来的变量会变成双字节字符
    vicker
        4
    vicker  
    OP
       2017-08-28 09:47:40 +08:00
    @jingniao 感谢帮助,前两天一直困扰的问题,在解决之后都看通了,最后通过用 string_escape 编码绕过实现了需求
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3422 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:04 · PVG 19:04 · LAX 04:04 · JFK 07:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.