简体   繁体   中英

Python3 Print Function

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM