记录我踩过的Python2中的一些坑

前言

狗头一出(开)生(始)就是学的Python3,但是公司一些已有的代码是Python2写的,为了图个方便,我也就开始使用起了Python2。慢慢的发现,其实Python2中有许多简便的地方,比如令人上瘾的print不用加括号:),当然也有许多坑。本文的目的就是记录我作为一个Python3用户在Python2中踩过的坑(其实也不算是坑,就是与3不一样的地方),以及解决办法,不定期更新。

oh,话说Python2似乎2020年1月1日就要退役了,当然用还是可以用的。

下面开始罗列,按踩坑的时间前后

1. list含中文无法正常print

s = ['hello','世界']
print s
#  ['hello', '\xe4\xb8\x96\xe7\x95\x8c']

解决方法:

s2 = str(s).decode("string_escape")
print s2
# ['hello', '世界']

2. input string 报错

使用input时只能输入数字,无法输入字符串的问题

s=input('请输入字符串:')
# 请输入字符串:hello
# ---------------------------------------------------------------------------
# NameError                                 Traceback (most recent call last)
# <ipython-input-1-c85d49e3280b> in <module>()
# ----> 1 s=input('请输入字符串:')
#
# <string> in <module>()
#
# NameError: name 'hello' is not defined

解决方法:

使用raw_input

s2=raw_input("请输入字符串:")
# 请输入字符串:hello
print s2
# hello
posted @ 2019-12-27 11:24  MrDoghead  阅读(297)  评论(0编辑  收藏  举报