V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
explist
V2EX  ›  Python

格式化字符串疑问

  •  
  •   explist · Dec 4, 2016 · 2172 views
    This topic created in 3431 days ago, the information mentioned may be changed or developed.

    s = ['0.3','1.25','12.98','2']

    s=map(lambda x:format(float(x),'>5.2f'),s)
    
    print(list(s))
    

    #[' 0.30', ' 1.25', '12.98', ' 2.00']

    转化后还是字符串,格式类似>5.2f,后面不足的补0,前面不足的补空格

    7 replies    2016-12-04 23:02:08 +08:00
    explist
        1
    explist  
    OP
       Dec 4, 2016
    有没有什么格式可以一步到位的?
    suspended
        2
    suspended  
       Dec 4, 2016
    看我大 ruby 一句话搞掂:
    ```ruby
    irb(main):007:0> ['0.3','1.25','12.98','2'].map {|x| '% 2.2f' % x.to_f}
    => [" 0.30", " 1.25", " 12.98", " 2.00"]
    ```
    suspended
        3
    suspended  
       Dec 4, 2016
    搞错。。。啊,不能删 /改回复? - -!
    thekoc
        4
    thekoc  
       Dec 4, 2016
    @explist 什么叫一步到位
    Kisesy
        5
    Kisesy  
       Dec 4, 2016
    print(['%5.2f'%float(x) for x in ['0.3','1.25','12.98','2']])
    一行到位
    explist
        6
    explist  
    OP
       Dec 4, 2016
    直接用格式化的相关函数如 format(),zfill()等
    lonelinsky
        7
    lonelinsky  
       Dec 4, 2016
    [ '{: >5.2f}'.format(float(x)) for x in s ] 这个应该可以
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5773 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 01:47 · PVG 09:47 · LAX 18:47 · JFK 21:47
    ♥ Do have faith in what you're doing.