6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python2.7 で平仮名とカタカナを逆転させる

Posted at

やりたいこと

  • ドラえもん => どらエモン にする

やったこと

text = u'ドラえもん 新・のび太の大魔境'
d = dict([(x, unichr(x - 0x60)) for x in xrange(ord(u'ァ'), ord(u'ヴ')+1)] + [(x - 0x60, unichr(x)) for x in xrange(ord(u'ァ'), ord(u'ヴ')+1)])
print text.translate(d)

結果

どらエモン 新・ノビ太ノ大魔境

なにこれ?

  • UTF-8 の平仮名と片仮名の差は 0x60 であることを利用して、平仮名→カタカナ、カタカナ→平仮名のマップを作ります。
  • str.translate を使って変換。

unicode のことしか考えてないので入力のバリデーションは必要かも。

6
4
1

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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?