Python3 Print Function

孤街浪徒 提交于 2021-02-08 11:55:29

问题


This probably an easy question but I just can't seem to make it work consistently for different permutations.

What is the Python3 equivalent of this?

print >> sys.stdout, "Generated file: %s in directory %s\n" % (name+".wav", outdir)

I've tried

print("String to print %s %s\n", file=sys.stdout % (var1, var2))

and

print("String to print {} {}\n".format(var1, var2), file=sys.stdout)

What is the best way to do this in Python3 now that the >> operator is no more. I know the % () has the be within the closing parenthesis of the print function but I always have trouble when using formatting as well as printing to a specific file/stream at the same time.


回答1:


Put the percent right next to the end of the string literal.

print("String to print %s %s\n" % (var1, var2), file=sys.stdout)

The percent operator is just like any other binary operator. It goes between the two things it's operating on -- in this case, the format string and the format arguments. It's the same reason that print(2+2, file=sys.stdout) works and print(2, file=sys.stdout + 2) doesn't.


(personal opinion corner: I think format is way better than percent style formatting, so you should just use your third code block, which behaves properly as you've written it)



来源:https://stackoverflow.com/questions/28347411/python3-print-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!