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

Python3.5 格式化遇到的问题

  •  
  •   baizexi · 2015-11-23 09:13:39 +08:00 · 2785 次点击
    这是一个创建于 3085 天前的主题,其中的信息可能已经有所发展或是发生改变。

    '%2d-%02d' % (3, 1)
    ' 3-01'
    '%.2f' % 3.1415926
    '3.14'
    '%2f'%3.1415926
    '3.1241593'

    请问 1 、 2 两行是什么意思呢?
    后两个式子为什么差一个标点结果也不同呢?谢谢

    11 条回复    2015-11-23 10:34:47 +08:00
    livevilwt
        1
    livevilwt  
       2015-11-23 09:20:11 +08:00
    你应该去看看 python 格式化的语法
    baizexi
        2
    baizexi  
    OP
       2015-11-23 09:26:05 +08:00
    @livevilwt 嗯嗯,最近在看廖学峰的教程,请问还有什么推荐的自学网站吗?
    PeterD
        3
    PeterD  
       2015-11-23 09:37:10 +08:00
    imn1
        4
    imn1  
       2015-11-23 10:04:51 +08:00
    happlebao
        5
    happlebao  
       2015-11-23 10:06:08 +08:00
    <img></img>
    用的跟你不是一个 python 系列。
    sunoru
        6
    sunoru  
       2015-11-23 10:11:39 +08:00
    %2d 表示这个整数输出至少有两位,前面用空格补足(%2f 也是类似的意思
    %02d 表示至少有两位,前面用 0 补足
    %.2f 表示保留到小数点后 2 位
    imn1
        7
    imn1  
       2015-11-23 10:15:13 +08:00
    最后那个应该算是误写
    f 是应该带小数点的,没有小数点默认是 6 位,前面那个 2 不起作用
    imn1
        8
    imn1  
       2015-11-23 10:20:24 +08:00
    In [5]: '%7f'%3.1415926
    Out[5]: '3.141593'

    In [6]: '%-f'%3.1415
    Out[6]: '3.141500'

    In [7]: '%f'%3.1415
    Out[7]: '3.141500'

    In [8]: '%.f'%3.1415
    Out[8]: '3'
    sunoru
        9
    sunoru  
       2015-11-23 10:23:19 +08:00
    @imn1 不加小数点不是完全不起作用,比如
    In [1]: "%9f" % 1.23
    Out[1]: ' 1.230000'
    baizexi
        10
    baizexi  
    OP
       2015-11-23 10:29:09 +08:00
    @sunoru
    @imn1
    @sunoru
    @imn1
    @PeterD 谢谢各位!
    imn1
        11
    imn1  
       2015-11-23 10:34:47 +08:00
    @sunoru
    因为 f 默认就是 6 位小数啊,跟前面的数字没关系,我说的是那数字不起作用
    In [10]: '%f'%1
    Out[10]: '1.000000'
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2285 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 05:29 · PVG 13:29 · LAX 22:29 · JFK 01:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.