python2代码到python3 print的正则替换
原文地址:
python2代码搬运到python3要改很多print? 试试用pyCharm的正则表达式替换
1.print 函数正则替换
在做数据挖掘比赛的时候,网上给的baseline 代码总是会有python 2.x 到python 3.x 的适配问题,多次出现所有在这里记录一下。
我用的是python 3.6版本。
最常遇到的就是print 函数
例如:
print "batch size: {}".format(batch_size)
在python 3.x 版本下会报错。
正确写法如下
print("batch size: {}".format(batch_size))
在网上查找了一下,参考文章里面是pycharm有正则替换,我发现我用的sublime text 3 也有正则替换。
我的写法如下
#find print (.*)
# print 后带1空格
#replace print($1)
不懂写正则表达式可以参考这个网址,即写即用就好,一般不背。
正则表达式书写
2. print 函数 在py 2.x 和 3.x区别
原文地址
python2的print和python3的print()
在这里再简单啰嗦几句print语句。
其实我们常用2.x的print 不是函数。
如:
print "There is only %d %s in the sky."%(1,'sun')
# 输出 There is only 1 sun in the sky.
3.x 的print 成了函数
如:
print("There is only %d %s in the sky."%(1,'sun'))
# 输出 There is only 1 sun in the sky.
根本原因是
python2.x中print语句的格式化输出源自于C语言的格式化输出,这种语法对于C这种静态语言比较适用,但是对于拥有很多先进数据结构的python来说就有点力不从心了。python的元组,列表,字典,集合等不适合用这种结构表示,这些数据结构大多元素用下标表示,在这种结构中写出来很混乱。
python 3.x 可使用格式化输出函数format()可以对有下标的数据结构输出更加直观方便。
如:
print("{0} is {1}.".format('Aoko','good'))
#输出 Kaito has 5 dollars.
name=["Kaito",5]
print("{0[0]} has {0[1]} dollars.".format(name))
#输出 Aoko is good.