14s}{c2}{nick_na...">

Python character alignment in python

I have difficulty aligning Japanese characters in python.

the code:

print "{c1}{name:>14s}{c2}{nick_name:>14s}{planes:>16s}".format(
    name=name, nick_name=nick_name, planes=planes, 
    c1=u.color['yellow'], c2=u.color['default']
)

Result: enter image description here

If the string contains only English and numbers, then .format () works fine, as shown on the right.

When matching with Japanese characters, alignment does not work as shown on the left.

Interestingly, when aligned with {name:>14s}:

  • If "name" contains 4 JP characters, there will be two prefix spaces.
  • If the "name" contains 3 JP characters, there will be 5 prefix spaces.
  • If "name" contains 2 JP characters, there will be 8 prefix spaces.
  • If the "name" contains 0 JP characters, there will be 14 prefix spaces.

It seems that in this case it processes 1 Japanese charater = 3 spaces.

{name:<14s} {name:^14s} {name:>14s} all have the behavior described above.

OSX 10.10.2, - monaco.

, - /.

, , ?

.


:

- .

  • , unicode Python, , .

  • "\ u3000" - CJK. . .

  • . .

  • SO, , Python.

, , - . .

enter image description here

+4
1

goofups:

  • UTF-8 .
  • , .

unicode str s. .

>>> print '{:>8s}'.format('ありがとう')
ありがとう
>>> print u'{:>8s}'.format(u'ありがとう')
   ありがとう
>>> print u'{:\u3000>8s}'.format(u'ありがとう')
   ありがとう
+3

Source: https://habr.com/ru/post/1583805/


All Articles