LoginSignup
0
1

More than 5 years have passed since last update.

UI > メッセージ は全角で入力して下さい。> 全角の"(”と")"と"."はダメ、の意味 | Python3: 半角チェック

Last updated at Posted at 2017-12-16

とある宅急便の問合せページでメッセージを書いて送信しようとした。

メッセージ は全角で入力して下さい。

全ての文字を「全角」にしたが、エラーは消えない。

試しに「全角」の"(”と")"と"."を消してみたところ送信できた。

不備

  1. 特殊記号の全角が使用不可であるならば、その旨を記載すべき
    • 全角の"「"と"」"は問題ない
  2. どの文字が全角でないかのエラーメッセージを表示した方が良い
    • そうでないため、「どの文字がエラーなのか」とユーザが探すことになる

Python3 半角チェック

v0.1 > .isalnum()使用

参考: [修正] Python 文字列の英数字判定でハマった@shiracamus さんのコメント

words = '''あいう'12"3456'''

print("半角の文字は以下です")
for elem in words:
    if elem.encode('utf-8').isalnum():
        print(elem)

run
半角の文字は以下です
1
4

v0.2 > len()使用

words = '''あいう'12"3456'''

print("半角の文字は以下です")
for elem in words:
    if len(elem.encode('utf-8')) == 1:
        print(elem)

run
半角の文字は以下です
'
1
"
4

まだ未対応の半角文字もありそう。

v0.3 > unicodedata使用

https://ideone.com/7WIXdX (Python 3.5)

import unicodedata

words = '''あいう'12"3456'''

print("半角の文字は以下です")
for elem in words:
    res = unicodedata.east_asian_width(elem)
    if res == 'Na':
        print(elem)

print("全文字のeast_asian_width()結果")
for elem in words:
    res = unicodedata.east_asian_width(elem)
    print(elem, res)

run
半角の文字は以下です
'
1
"
4
全文字のeast_asian_width()結果
あ W
い W
う W
' Na
1 Na
2 F
" Na
3 F
4 Na
5 F
6 F
0
1
0

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
0
1