如何替换所有:打印“字符串",在 Python2 中:打印(“字符串"),对于 Python3? [英] How to replace all: print "string", in Python2 with: print("string"), for Python3?

查看:62
本文介绍了如何替换所有:打印“字符串",在 Python2 中:打印(“字符串"),对于 Python3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如标题所说,如何将 Python2 中的 all:print "string", 替换为:print("string"), for Python3?

As the title says, how to replace all: print "string", in Python2 with: print("string"), for Python3?

真的希望他们使这一功能向后兼容.官方推荐使用 2to3.py 脚本,但它似乎总是我需要在 Py2 脚本示例中替换的打印语句,比如在笔记本或 Jupyter 实验室中运行(这使得 2to3.py 不那么吸引人 - 除非他们实施转换器!)

I really wish they made this one function backward compatible. Officially the 2to3.py script is recommended, but it always seems like its just the print statements that i need to replace in Py2 script examples, say running in a notebook or Jupyter lab (which makes the 2to3.py less appealing - unless they implemented a converter!)

.

@Bazingaa、@Wiktor Stribiżew、@jpp:不重复,即不转发兼容性.即,我不是在问如何在 Python2 中使用 Python3 语法,这将是向前兼容,但相反的是反向兼容.

@Bazingaa, @Wiktor Stribiżew, @jpp: Not duplicate, i.e. not forwards compatiblity. I.E., I'm not asking how to use Python3 syntax in Python2, which would be forwards compatiblity, but the opposite which is reverse compatibility.

@jpp 我对你的阅读理解水平感到震惊,即使在添加说明之后也是如此.我最初在下面的答案中包含了那些可能的重复项",并解释了其中的区别(在添加标签和评论之前,您肯定也没有阅读这些内容),它们并没有给我我正在寻找的东西".感谢危险"警告,但您又一次错过了重点,我使用的是 Python 3..试图在旧教程脚本中更改 Python 2 的语法.不知道你怎么会读错两次.我的以下解决方案是有效的,这是我多年来一直在寻找的解决方案,毫无疑问会帮助到这里的其他人.

@jpp I'm shocked at your level of reading comprehension, even after adding clarification. I included those 'possible duplicates' originally in my answer below and explained the difference (which you must have also failed to read before adding your tags and comment), which do not 'give me what I'm looking for'. Appreciate the 'peril' caution, but again you missed the whole point, that I'm using Python 3.. trying to change the syntax from Python 2 in old tutorial scripts. Don't know how you could read that incorrectly twice. My solution below is valid, one I've looked for for years, and will undoubtedly help others who land here.

推荐答案

这个this 显示 Vim 的解决方案,但这个适用于 Windows 并打印变量语句.

This and this show solutions for Vim, but this one works for Windows and print variable statements.

在旧的 Python2 示例脚本中运行良好.否则使用 2to3.py 进行额外的转换.

Works well in old Python2 example scripts. Otherwise use 2to3.py for additional conversions.

regexr.com 上试用一下(由于某种原因在 NP++ 中不起作用):

Try it out on regexr.com (doesn't work in NP++ for some reason):

find:    (?<=print)( ')(.*)(')
replace: ('$2')

对于变量:

(?<=print)( )(.*)(\n)
('$2')\n

对于标签和变量:

(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n

这篇关于如何替换所有:打印“字符串",在 Python2 中:打印(“字符串"),对于 Python3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆