brackets around print in python

后端 未结 3 1406
情歌与酒
情歌与酒 2020-12-16 05:59

I have this line of code in python

print \'hello world\'

against

print (\'hello world\')

can someone tel

相关标签:
3条回答
  • 2020-12-16 06:07

    I landed here on my search for regex to convert these syntaxes. Here is my solution for others:

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

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

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

    for variables:

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

    for label and variable:

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

    How to replace all print "string" in Python2 with print("string") for Python3?

    0 讨论(0)
  • 2020-12-16 06:21

    For Python 2, it makes no difference. There, print is a statement and 'hello' and ('hello') are its argument. The latter gets simplified to just 'hello' and as such it’s identical.

    In Python 3, the print statement was removed in favor of a print function. Functions are invoked using braces, so they are actually needed. In that case, the print 'hello' is a syntax error, while print('hello') invokes the function with 'hello' as its first argument.

    You can backport the print function to Python 2, by importing it explicitly. To do that add the following as the first import of your module:

    from __future__ import print_function
    

    Then you will get the same behaviour from Python 3 in Python 2, and again the parentheses are required.

    0 讨论(0)
  • 2020-12-16 06:23

    You should read what's new in python 3.0:

    The print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement (PEP 3105).

    Backwards Compatibility:

    The changes proposed in this PEP will render most of today's print statements invalid. Only those which incidentally feature parentheses around all of their arguments will continue to be valid Python syntax in version 3.0, and of those, only the ones printing a single parenthesized value will continue to do the same thing. For example, in 2.x:

    >>> print ("Hello", "world")  # without import
    ('Hello', 'world')
    
    >>> from __future__ import print_function  
    
    >>> print ("Hello", "world")       # after import 
    Hello world
    
    0 讨论(0)
提交回复
热议问题