0

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.

4
  • The second one, print("String to print {} {}\n".format(var1, var2), file=sys.stdout) works for me. Are you sure you have sys imported in your prompt? Commented Feb 5, 2015 at 15:17
  • To know the better way .... stackoverflow.com/questions/5082452/… Commented Feb 5, 2015 at 15:20
  • what is the first command supposed to achieve? Commented Feb 5, 2015 at 15:22
  • Yes I had sys imported. Not sure what the problem was, probably a typo but I wanted to figure out using % with the new print anyway. It's not supposed to achieve anything as it already prints to stdout, was just an example. Commented Apr 28, 2015 at 8:25

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

is this not the same as print("String to print {} {}\n".format(var1, var2), file=sys.stdout)?
Yeah. I'm interpreting the question as, "the first and third code blocks in my question work, but not the second. How do I get percent formatting to behave the same way format does?"
I was mostly also trying to understand using the % in Python3 so I could convert some python 2 code more easily. Yes I know 2to3 exists, but sometimes it's easier to just do it yourself in a few places.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.