推荐学习书目
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 · May 19, 2020 · 3497 views
    This topic created in 2201 days ago, the information mentioned may be changed or developed.
    a = 'PM2.5' ,b = '地下管道' ,c = '空铁 WIFI'
    print(a, '\t\t', 1)
    print(b, '\t\t', 2)
    print(c, '\t\t', 3)
    请教如何让数字对齐
    7 replies    2020-05-23 13:50:55 +08:00
    ClericPy
        1
    ClericPy  
       May 19, 2020
    1. 参考字符串的 ljust rjust center 等方法
    2. 参考字符串 format 的 < > = 字符串补齐格式
    3. 参考第三方库在命令行里打印 table
    4. 其他的一般也用不上...
    wingor2015
        2
    wingor2015  
       May 20, 2020
    print('{:<13}'.format(a), '\t\t', 1)
    print('{:<10}'.format(b), '\t\t', 2)
    print('{:<10}'.format(c), '\t\t', 3)
    TtTtTtT
        3
    TtTtTtT  
       May 20, 2020
    =。=命令行的话,难。

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

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

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

    对齐的话, 直接用在终端里打印 table 的库算了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2662 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 10:27 · PVG 18:27 · LAX 03:27 · JFK 06:27
    ♥ Do have faith in what you're doing.