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

关于 sys.stdout.write 的疑问

  •  
  •   pysama · 2014-10-10 23:33:22 +08:00 · 5130 次点击
    这是一个创建于 3479 天前的主题,其中的信息可能已经有所发展或是发生改变。
    python 实现下载进度条用到了这样的代码:sys.stdout.write("\r%2d%%" % percent)。求解释\r%2d%%这段字符串。(我查了string format的相关知识,也没有看到解释)
    10 条回复    2014-10-11 15:28:34 +08:00
    sandtears
        1
    sandtears  
       2014-10-10 23:57:52 +08:00 via Android   ❤️ 1
    \r 是格式控制代表回车
    %2d 代表长度为 2 的整数
    %% 就是一个 %
    jsq2627
        2
    jsq2627  
       2014-10-11 00:11:47 +08:00 via iPhone   ❤️ 1
    \r表示return,光标回到当前行首。所以能实现单行刷新的进度条效果。
    pysama
        3
    pysama  
    OP
       2014-10-11 09:43:19 +08:00
    @sandtears %2d 代表长度为 2 的整数,%% 就是一个 %,这里的%是不是可以理解为转义符一样呢
    有可以参考的详细文档吗?我想看个明白。 [自己没有搜索到

    @jsq2627 非常感谢
    tonghuashuai
        4
    tonghuashuai  
       2014-10-11 10:20:23 +08:00   ❤️ 1
    第二个 % 是转义,于是 %% 输出 %
    sandtears
        5
    sandtears  
       2014-10-11 10:54:48 +08:00 via Android
    @pysama 对,就是转义符。。文档的话,我也不记得在哪学的了@_@
    sandtears
        6
    sandtears  
       2014-10-11 10:55:55 +08:00 via Android   ❤️ 1
    @pysama 额我想起来了,其实这里和 C 语言很像,大多数情况参考 C 就行了
    pysama
        7
    pysama  
    OP
       2014-10-11 11:06:12 +08:00
    @hahastudio 召唤下haha大神 :)
    limbo0
        8
    limbo0  
       2014-10-11 11:17:45 +08:00   ❤️ 1
    python里格式化字符串和C语言是一样的
    hahastudio
        9
    hahastudio  
       2014-10-11 11:19:18 +08:00   ❤️ 1
    @pysama ha?我怎么就成大神了= =

    % 是旧世代的 string formatting 语法,可以在这里获得更多信息:
    https://docs.python.org/2/library/stdtypes.html#string-formatting

    顺带一提,Dive into Python 中提到,Python 使用 % 的语法与 C 的 sprintf 相同:
    http://www.diveintopython.net/native_data_types/formatting_strings.html

    新世代的 string formatting 语法是 {0} 这样的,可以在这里获得更多信息:
    https://docs.python.org/2/library/string.html#format-string-syntax
    pysama
        10
    pysama  
    OP
       2014-10-11 15:28:34 +08:00
    @hahastudio 因为在python区看到你回复的内容都是有理有据的。所以非常佩服haha~

    原来string formatting还有这么参数可以选择的。(之前只是看了A byte of python,所以没有深入了解),再次感谢haha
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2930 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 02:59 · PVG 10:59 · LAX 19:59 · JFK 22:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.