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

格式化字符串疑问

  •  
  •   explist · 2016-12-04 17:44:30 +08:00 · 1696 次点击
    这是一个创建于 2706 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2016-12-04 23:02:08 +08:00
    explist
        1
    explist  
    OP
       2016-12-04 17:50:12 +08:00
    有没有什么格式可以一步到位的?
    suspended
        2
    suspended  
       2016-12-04 18:28:12 +08:00
    看我大 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  
       2016-12-04 18:29:25 +08:00
    搞错。。。啊,不能删 /改回复? - -!
    thekoc
        4
    thekoc  
       2016-12-04 18:37:51 +08:00
    @explist 什么叫一步到位
    Kisesy
        5
    Kisesy  
       2016-12-04 18:44:55 +08:00
    print(['%5.2f'%float(x) for x in ['0.3','1.25','12.98','2']])
    一行到位
    explist
        6
    explist  
    OP
       2016-12-04 19:23:26 +08:00
    直接用格式化的相关函数如 format(),zfill()等
    lonelinsky
        7
    lonelinsky  
       2016-12-04 23:02:08 +08:00
    [ '{: >5.2f}'.format(float(x)) for x in s ] 这个应该可以
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   823 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:09 · PVG 06:09 · LAX 15:09 · JFK 18:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.