3

I recently started to use Python 3 and I understood that in this version, the print() function assumes that the string is unicode and not ASCII (8-bit chars).

Well, I know that my strings are sometimes ASCII, but I really don't care about it. Why should I always get an annoying b' prefix printed to the screen?

Is there a way to turn off this "feature" ?

My code:

proc = subprocess.Popen(diff_cmd, shell = True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
while proc.poll() is None:
    output = proc.stdout.readlines()
    for line in output:
        print(line)
SomethingSomething
  • 11,491
  • 17
  • 68
  • 126
  • Can you give an example string? – Bhargav Rao Mar 26 '15 at 11:57
  • 2
    Show your code, usually that means it's interpreting a byte stream – EdChum Mar 26 '15 at 11:57
  • 1
    See related: http://stackoverflow.com/questions/8102471/why-does-band-sometimes-b-show-up-when-i-split-some-html-sourcepython?rq=1 and http://stackoverflow.com/questions/16748083/suppress-print-without-b-prefix-for-bytes-in-python-3?rq=1 – EdChum Mar 26 '15 at 11:59
  • I think I understood what happened. When I use print with a string that I write in advance, it is automatically unicode and is ok. I read a program output so it was ASCII. Is the only way to deal with it is to convert each printed string to unicode? – SomethingSomething Mar 26 '15 at 12:00

1 Answers1

4

You need to be explicit about this yourself.

You need to specify the encoding and decode the bytes into Unicode (ASCII encoding): line.decode('ascii'). If object are sometimes bytes and sometimes Unicode then you need to handle this accordingly.

After that you can pass it to print().

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180