Printed length of a string in python

后端 未结 3 1006
旧巷少年郎
旧巷少年郎 2021-02-14 19:35

Is there any way to find (even a best guess) the \"printed\" length of a string in python? E.g. \'potaa\\bto\' is 8 characters in len but only 6 characters wide pr

3条回答
  •  攒了一身酷
    2021-02-14 19:50

    The printed length of a string depends on the type of the string.

    Normal strings in python 2.x are in utf-8. The length of utf-8 is equal to the bytes in String. Change the type to unicode, len() delivers now printed signs. So Formatting works:

    value = 'abcäöücdf'
    len_value  = len(value)
    len_uvalue = len(unicode(value,'utf-8'))
    size = self['size'] + len_value-len_uvalue
    print value[:min(len(value),size)].ljust(size)
    

提交回复
热议问题