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

请教如何对齐

  •  
  •   songdg · 2020-05-19 22:31:31 +08:00 · 2768 次点击
    这是一个创建于 1409 天前的主题,其中的信息可能已经有所发展或是发生改变。
    a = 'PM2.5' ,b = '地下管道' ,c = '空铁 WIFI'
    print(a, '\t\t', 1)
    print(b, '\t\t', 2)
    print(c, '\t\t', 3)
    请教如何让数字对齐
    7 条回复    2020-05-23 13:50:55 +08:00
    ClericPy
        1
    ClericPy  
       2020-05-19 22:34:16 +08:00
    1. 参考字符串的 ljust rjust center 等方法
    2. 参考字符串 format 的 < > = 字符串补齐格式
    3. 参考第三方库在命令行里打印 table
    4. 其他的一般也用不上...
    wingor2015
        2
    wingor2015  
       2020-05-20 12:36:13 +08:00
    print('{:<13}'.format(a), '\t\t', 1)
    print('{:<10}'.format(b), '\t\t', 2)
    print('{:<10}'.format(c), '\t\t', 3)
    TtTtTtT
        3
    TtTtTtT  
       2020-05-20 13:57:33 +08:00
    =。=命令行的话,难。

    首先,需要一个能对齐的字体。。因为数字、字母和中文文字都不是等宽的。

    如果找得到等宽的话,把所有字符映射成显示长度,取最大,然后不满足长度的补足即可。
    当然啦,这也很复杂,因为要是覆盖边缘 case 的话,就要对控制字符之类的逻辑进行特殊处理。

    我刚才顺手看了眼 VS code 的实现,估计就是把中文文字当 2,其他当 1,因为半个省略号竟然长度算 1 。。
    songdg
        4
    songdg  
    OP
       2020-05-23 12:32:31 +08:00
    @wingor2015 谢谢,不过不太行。
    songdg
        5
    songdg  
    OP
       2020-05-23 12:33:15 +08:00
    @ClericPy 都试过了,感觉都不怎么齐。
    songdg
        6
    songdg  
    OP
       2020-05-23 12:33:30 +08:00
    @TtTtTtT 还是放弃算了。
    ClericPy
        7
    ClericPy  
       2020-05-23 13:50:55 +08:00
    @songdg #5 不齐的原因可能你不是等宽字体?

    对齐的话, 直接用在终端里打印 table 的库算了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1017 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:25 · PVG 03:25 · LAX 12:25 · JFK 15:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.