I have difficulty aligning Japanese characters in python.
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:
If the string contains english and numbers only, the .format() works fine,as shown on the right.
The aligning goes wrong when encountering Japanese characters, as shown on the left.
Interestingly, when aligning with {name:>14s}
:
It seems like it treat 1 Japanese charater = 3 spaces in this case.
{name:<14s}
{name:^14s}
{name:>14s}
all have the behavior mentioned above.
I am using OSX 10.10.2, terminal font is monaco.
Maybe this has something to do with full-width/half-width characters.
Is there anyway to align Japanese characters just like English characters?
Thanks you.
Edit:
Ignacio Vazquez-Abrams's answer is indeed the correct way.
Everyone who is dealing with unicode in Python should read the slide he pointed out.
The "\u3000" is the full-width space in CJK. See this page.
Review the .Format Syntax would also help.
I would also like to recommend this SO answer which helps me understanding how unicode works in Python.
However, if the string contains both half-width and full-width characters, the alignment still goes wrong. A simple workaround is to use all full-width characters.
You can use the :> , :< or :^ option in the f-format to left align, right align or center align the text that you want to format. We can use the fortmat() string function in python to output the desired text in the order we want.
Alignment of Strings Using the format() Method in Python For the alignment of strings, we use the same syntax we used for the alignment of numbers. To left-align a string, we use the “:<n” symbol inside the placeholder.
The string rjust() method returns a right-justified string of a given minimum width. The syntax of rjust() method is: string.rjust(width[, fillchar])
You're performing two goofups simultaneously:
For the first, use unicode
s instead of str
s. For the second, use full-width spaces instead.
>>> print '{:>8s}'.format('ありがとう')
ありがとう
>>> print u'{:>8s}'.format(u'ありがとう')
ありがとう
>>> print u'{:\u3000>8s}'.format(u'ありがとう')
ありがとう
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With