Home  >  Q&A  >  body text

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 days ago633

reply all(4)I'll reply

  • PHP中文网

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

    Change the font of the terminal to a fixed-width font, such as the more eye-catching Consolas, Adobe's open source font Source Code Pro...

    reply
    0
  • 天蓬老师

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

    The length of Unicode strings is calculated based on the number of characters rather than the "displayed width". A Chinese character and a Western character are both counted as 1, so they are not aligned. You can use the additional wcwidth package to calculate the number of cells occupied by a character.

    reply
    0
  • 天蓬老师

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

    The solution is to use Chinese full-width space padding, which should help you.

    >>> 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))+'|')
    乌鲁木齐  |
    >>> 

    reply
    0
  • 天蓬老师

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

    segmentfault.com/q/1010000008288733/a-1020000008291692

    reply
    0
  • Cancelreply