python2 升级 python3 的一些变化

sort 和 sorted

  • python2
sort(cmp =  _ _cmp_ _ (), key = None, reverse = False)

cmp 参数为响应的比较函数,未指定默认调用 _ cmp _ ()(Should return a negative integer if self < other, zero if self == other, a positive integer if self > other.), cmp()

  • python3
sort(key = None, reverse = False)

制定比较函数可以使用 lambda 或者 cmp_to_key()

dict.keys()

  • python2 返回 key list
  • python3 返回的是可迭代对象,需要手转 list(xx.keys())

字符串与字节流

python3 中将字符串和字节流进行了严格区分,分别由 str 和 bytes 表示。
bytes 由 b 开头,假如使用 subprocess.check_output() 中返回的是字节字符串,如果需要以字符串方式(python 3)使用需要手动转换成 str

#!/usr/bin/env python3

b = b"test_str"
# bytes -> str
print(b)
print(str(b, encoding = "utf8"))
print(b.decode())

print("------")

s = "test_str"
# str -> bytes
print(s)
print(bytes(s, encoding = "utf8"))
print(s.encode())

raw_input 删除

如果想要兼容 python2 和 python3,可以使用 try:input = raw_input except xxx:pass 的形式替换,或者使用兼容 python2 和 python3 的库,six 等

参考:
https://docs.python.org/2/library/functions.html#sorted
https://docs.python.org/2.7/library/subprocess.html#subprocess.check_output

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值