Python
error
example
stringOperation

Python > try, except > UnicodeError 実装例

動作環境
ideone (Python 3.5)

@ Scipy lecture notes, Edition 2017.1
https://www.scipy-lectures.org/_downloads/ScipyLectures-simple.pdf
p45

UnicodeErrorのエラー補足例がある。

参考にして実装してみた。

https://ideone.com/t3h7di

def filter_name(name):
    try:
        name = name.encode('ascii')
    except UnicodeError as e:
        raise e
    return name

res = filter_name('7of9')
print(res)
res = filter_name('7之9')
print(res)
stdout
7of9
stderr
Traceback (most recent call last):
  File "prog.py", line 10, in <module>
  File "prog.py", line 5, in filter_name
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)

link