20
20

More than 5 years have passed since last update.

Pythonのunicodedataライブラリを使って、全角文字も半角文字も揃えて表示する

Last updated at Posted at 2016-07-18

目的

pythonで、ちょっと文字列を揃えて表示しようとした時
全角と半角をごちゃ混ぜにすると・・・

# サンプル
print("%-10s : %s" % ("タコライス", "おいしい"))
print("%-10s : %s" % ("Curry", "Spicy!"))
print("%-10s : %s" % ("タコワサ将軍", "食べられない・・・"))

# 結果
タコライス      : おいしい
Curry      : Spicy!
タコワサ将軍     : 食べられない・・・

10文字ごとに「:」で分けたいのに、こんな感じでうまく揃わないことがある。
unicodedataライブラリを使うと、この辺りをサクッと解決できた。

unicodedata参考リンク
http://docs.python.jp/3.5/library/unicodedata.html

環境

python のバージョンは 3.5.1
OS は CentOS 7.1

試した時期は 2016年の7月

全角半角を判定する

unicodedata.east_asian_width 関数を使うと、east asian width の値を返してくれるので、文字が半角なのか全角なのかを調べることができる。
east asian width は「F, H, W, Na, A, N」の6種類が定められていて、
F, W, A の3つが全角文字とされている。

east asian width参考リンク
https://ja.wikipedia.org/wiki/%E6%9D%B1%E3%82%A2%E3%82%B8%E3%82%A2%E3%81%AE%E6%96%87%E5%AD%97%E5%B9%85

使ってみると、こんな感じだ。

# サンプル
import unicodedata
unicodedata.east_asian_width('a')
unicodedata.east_asian_width('あ')

# 結果
'Na'
'W'

全角半角どちらも整列できるようにする

上記の関数を利用して、「指定した文字列が半角何文字分なのか」を調べれば、
全角/半角のどちらでも文字列を整列させることができる。

左寄せ用の、こんな関数を作ってみた。

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

使ってみる。

# サンプル
print("%s : %s" % (left(10, "タコライス"), "おいしい"))
print("%s : %s" % (left(10, "Curry"), "Spicy!"))
print("%s : %s" % (left(10, "タコワサ将軍"), "食べられない・・・"))

# 結果
タコライス : おいしい
Curry      : Spicy!
タコワサ将軍   : 食べられない・・・

・・・・。
web上だとわかりづらいね、画像も載せておきます。
20160718_qiita用.png

これで、全角文字も半角文字も揃えて表示することができるようになった。

・・・右寄せするには、
「return msg + ' '*digit」を「return ' '*digit + msg」
に変えれば対応できる。

以上

20
20
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
20