我希望我的函数返回编码。用户应该导入它。但是,如果用户按 Enter 键,该函数应返回 windows-1250 作为默认编码。
当我运行此代码时,出现错误:
如果 enc == '': ^ 缩进错误:意外缩进
def encoding_code(prompt):
"""
Asks for an encoding,
throws an error if not valid encoding.
Empty string is by default windows-1250.
Returns encoding.
"""
while True:
enc = raw_input(prompt)
if enc == '':
enc = 'windows-1250'
try:
tmp = ''.decode(enc) # Just to throw an error if not correct
except:
print('Wrong input. Try again.')
continue
break
return enc
您正在混合制表符和空格
之前 if 您使用了一个空格和两个制表符
在 python 中,你不应该混合使用制表符和空格,你应该使用 tab 或 space
您可以使用
python -tt script.py
找到
大多数 Python 开发人员更喜欢
space to tab
Python 通常要求您在代码中具有相同级别的缩进(通常是 4 个空格的倍数,这与单个制表符基本相同)。
def encoding_code(prompt):
"""
Asks for an encoding,
throws an error if not valid encoding.
Empty string is by default windows-1250.
Returns encoding.
"""
while True:
enc = raw_input(prompt)
if enc == '':
enc = 'windows-1250'
try:
tmp = ''.decode(enc) # Just to throw an error if not correct
except:
print('Wrong input. Try again.')
continue
break
return enc