When trying to display a little aligned character string in python If you mix full-width and half-width characters ...
#sample
print("%-10s : %s" % ("Taco rice", "Delicious"))
print("%-10s : %s" % ("Curry", "Spicy!"))
print("%-10s : %s" % ("General Tacowasa", "I can not eat···"))
#result
Taco rice:Delicious
Curry : Spicy!
General Tacowasa:I can not eat···
Sometimes I want to separate every 10 characters with ":", but they don't line up like this. Using the unicodedata library, I was able to solve this area quickly.
unicodedata reference link http://docs.python.jp/3.5/library/unicodedata.html
The version of python is 3.5.1 OS is CentOS 7.1
I tried it in July 2016
The unicodedata.east_asian_width function returns a value of east Asian width, so you can check whether a character is half-width or full-width. There are 6 types of east Asian width, "F, H, W, Na, A, N". Three characters, F, W, and A, are double-byte characters.
east Asian width reference link https://ja.wikipedia.org/wiki/東アジアの文字幅
When I use it, it looks like this.
#sample
import unicodedata
unicodedata.east_asian_width('a')
unicodedata.east_asian_width('Ah')
#result
'Na'
'W'
If you use the above function to find out "how many half-width characters the specified character string is", Character strings can be aligned in either full-width or half-width.
I made a function like this for left justification.
import unicodedata
def left(digit, msg):
for c in msg:
if unicodedata.east_asian_width(c) in ('F', 'W', 'A'):
digit -= 2
else:
digit -= 1
return msg + ' '*digit
I will try it.
#sample
print("%s : %s" % (left(10, "Taco rice"), "Delicious"))
print("%s : %s" % (left(10, "Curry"), "Spicy!"))
print("%s : %s" % (left(10, "General Tacowasa"), "I can not eat···"))
#result
Taco rice:Delicious
Curry : Spicy!
General Tacowasa:I can not eat···
・ ・ ・ ・. It's hard to understand on the web, so I'll post an image as well.
Now it is possible to display both full-width and half-width characters.
・ ・ ・ To right justify "Return msg +'"* digit" to "return''* digit + msg" It can be dealt with by changing to.
that's all
Recommended Posts