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.

ss7
  • 2,902
  • 7
  • 41
  • 90
  • 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? – Anshul Goyal Feb 05 '15 at 15:17
  • To know the better way .... http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format – Bhargav Rao Feb 05 '15 at 15:20
  • what is the first command supposed to achieve? – Padraic Cunningham Feb 05 '15 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. – ss7 Apr 28 '15 at 08:25

1 Answers1

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)

Kevin
  • 74,910
  • 12
  • 133
  • 166
  • 3
    is this not the same as `print("String to print {} {}\n".format(var1, var2), file=sys.stdout)`? – Padraic Cunningham Feb 05 '15 at 15:17
  • 2
    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?" – Kevin Feb 05 '15 at 15:18
  • 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. – ss7 Apr 28 '15 at 08:23