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
fxxkgw
V2EX  ›  Python

python 路径字符串替换问题

  •  
  •   fxxkgw · 2016-09-26 16:26:26 +08:00 · 2239 次点击
    这是一个创建于 2769 天前的主题,其中的信息可能已经有所发展或是发生改变。
    i = '/export/server/xxx/bin/test'

    我要把'/'替换成'\/'

    i = '\/export\/server\/xxx\/bin\/test'

    但是用了 i.replace 和 re.sub 方法得到的都是
    \\/export\\/server\\/xxx\\/bin\\/test

    请问这个需求怎么实现呢?
    7 条回复    2016-09-26 18:31:03 +08:00
    RIcter
        1
    RIcter  
       2016-09-26 16:28:42 +08:00
    你得 print ,不 print 怎么看都是 \\/
    raysonx
        2
    raysonx  
       2016-09-26 16:29:15 +08:00
    为什么要替换?楼主要手动 encode 和 decode ?
    fxxkgw
        3
    fxxkgw  
    OP
       2016-09-26 16:31:02 +08:00
    @RIcter 是的 用 print 就正常 但我需要获取这个值 用字符串的 format 格式也不行


    @raysonx 想获取值然后调用 shell 脚本执行 shell 里面的 sed 需要的是字符串 不是路径
    raysonx
        4
    raysonx  
       2016-09-26 16:36:38 +08:00
    @fxxkgw 非得调用 shell 脚本吗?手动处理很容易出现注入。
    littleshy
        5
    littleshy  
       2016-09-26 17:15:25 +08:00
    /又不需要转义,怎么可能出现\/这种东西……
    aiver
        6
    aiver  
       2016-09-26 18:02:38 +08:00
    @fxxkgw 你用 i.replace 后就是你要的格式了,里面出现\\V 是系统显示的效果,因为\需要转义,你用 print 就是实际的字符串了,不要纠结它在系统的表现形式
    imn1
        7
    imn1  
       2016-09-26 18:31:03 +08:00
    sed 用#做分隔符就不需要转义了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   945 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 20:27 · PVG 04:27 · LAX 13:27 · JFK 16:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.