ss7
ss7

Reputation: 3012

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.

Upvotes: 0

Views: 1020

Answers (1)

Kevin
Kevin

Reputation: 76254

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)

Upvotes: 3

Related Questions