Heim  >  Fragen und Antworten  >  Hauptteil

ubuntu - Python3.x的中文字符在Linux下面的占位问题?

运行环境:python3.x + ubuntu

def print_table(table):
    max_width = 0  # 取table中最长元素
    for x in table:
        if len(x) > col_width:
            max_width = len(x)
    max_width = max_width * 2

    for x in table:
        print('{:{}}'.format(x, max_width) + '|')

英文可以正常对齐:

>>> en = ['hello', 'world', 'hi', 'bug']
>>> print_table(en)
hello     |
world     |
hi        |
bug       |

中文无法无法正常对齐:

>>> ch = ['上海', '北京', '黑龙江', '乌鲁木齐']
>>> print_table(ch)
上海      |
北京      |
黑龙江     |
乌鲁木齐    |

请问这是什么原因?我观察了一下好像是中文字符在终端下面的输出都是占用了两个空格,但是英文只占用了一个空格。如果是这样,有什么好的解决方法?

迷茫迷茫2741 Tage vor631

Antworte allen(4)Ich werde antworten

  • PHP中文网

    PHP中文网2017-04-18 10:27:49

    更换终端的字体,更换为等宽字体,像比较养眼的Consolas,Adobe 的开源字体 Source Code Pro...

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:27:49

    Unicode字符串算长度是按照字符数而不是“显示出来的宽度”,一个汉字和一个西文都算1的,所以对不齐。可以用额外的wcwidth包来计算字符占用的格子数。

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:27:49

    解决办法是使用中文全角空格填充,应该对你有帮助。

    >>> print("{:{space}<6s}".format("上海", space=chr(12288))+'|')
    上海    |
    >>> print("{:{space}<6s}".format("北京", space=chr(12288))+'|')
    北京    |
    >>> print("{:{space}<6s}".format("黑龙江", space=chr(12288))+'|')
    黑龙江   |
    >>> print("{:{space}<6s}".format("乌鲁木齐", space=chr(12288))+'|')
    乌鲁木齐  |
    >>> 

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:27:49

    segmentfault.com/q/1010000008288733/a-1020000008291692

    Antwort
    0
  • StornierenAntwort