8 ms·
What is the advantage of python 2 print over python 3 print? I believe that python 3 print can do everything python 2 print can do on the same level of elegancy
by wonjohnchoi 13y ago
What is the advantage of python 2 print over python 3 print? I believe that python 3 print can do everything python 2 print can do on the same level of elegancy. Also, python 2 print has a weird trailing-comma syntax. When a trailing comma is added to a print statement, a space is printed when another print statement is used. For example,
print 'hi', # prints hi (no extra space in the end)
print 'hi',; print 'hi' # prints hi hi
I personally dislike this syntax because I don't find this natural. Wouldn't it make more sense to print an extra space after the print statement with trailing comma instead of before the next print statement?
- zephjc 13y agono trailing space is a convenient shorthand - print by itself prints with a newline (so it might make sense to have print() vs println()); print + comma omits the newline and waits for the next print statement, so that print 'hi', do_something() print 'there' and print 'hi', 'there' both yield hi there (Assuming do_something() doesn't call print itself)
- falcolas 13y agoFWIW: pprint = functools.partial(print, end=' ') pprint('hi') do_something() print('there') print('hi', 'there', sep=' ') I appreciate the fine grained control, and the ability to do things like `functools.partial` on it. fprint = functools.partial(print, file='/var/log/foo.log') fprint("I'm writing to a file!") fprint("So am I")
- Fede_V 13y agoI understand this, but couldn't you simply wrap print itself in a function, and do that in Python 2.7 already? Granted, your method saves you one line and it's more 'natural'.
- falcolas 13y agoNot really, since the Python 2 version is a keyword, and not a function, you can't simply provide keyword arguments to it. You would instead have to build up a string and eval it. It would have to be something like this (completely untested): def print_wrapper(*args, **kwargs) outfile = None print_stmt = "print " if 'file' in kwargs: outfile = open(kwargs['file'], 'a') print_stmt += '>>outfile ' print_stmt += ", ".join(*args) if 'end' in kwargs and kwargs['end'] == ' ': print_stmt += ',' eval(print_stmt) if outfile is not None: outfile.close() sep and other end values for anything other than ' ' would not be possible. http://docs.python.org/2.6/reference/simple_stmts.html#the-print-statement http://docs.python.org/2.6/reference/simple_stmts.html#the-p...