>>> s = 'auszuschließen'
>>> print(s.encode('ascii', errors='xmlcharrefreplace'))
b'auszuschließen'
>>> print(str(s.encode('ascii', errors='xmlcharrefreplace'), 'ascii'))
auszuschließen
Is there a prettier way to print any string without the b''
?
EDIT:
I'm just trying to print escaped characters from Python, and my only gripe is that Python adds "b''" when i do that.
If i wanted to see the actual character in a dumb terminal like Windows 7's, then i get this:
Traceback (most recent call last):
File "Mailgen.py", line 378, in <module>
marked_copy = mark_markup(language_column, item_row)
File "Mailgen.py", line 210, in mark_markup
print("TP: %r" % "".join(to_print))
File "c:\python32\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2026' in position 29: character maps to <undefined>
If you see utf-8, then your system supports unicode characters. To print any character in the Python interpreter, use a u to denote a unicode character and then follow with the character code. For instance, the code for β is 03B2, so to print β the command is print ('u03B2'). There are a couple of special characters that will combine symbols.
A couple commonly used symbols in engineers include Omega and Delta. We can print these in python using unicode characters. From the Python interpreter we can type: All of these are unicode characters.
In Python, Unicode characters are represented as a string type. These characters are printed using the print command. Before giving the hexadecimal value as an input value, the escape sequence \u is used before every hexadecimal value. Note that the hexadecimal value stored in the variable is taken as a string.
Python won't print it without converting it back into a string and the default conversion puts in the b and quotes. Using decode explicitly converts it back to a string; the default encoding is utf-8, and since your bytes only consist of ascii which is a subset of utf-8 it is guaranteed to work.
>>> s='auszuschließen…'
>>> s
'auszuschließen…'
>>> print(s)
auszuschließen…
>>> b=s.encode('ascii','xmlcharrefreplace')
>>> b
b'auszuschließen…'
>>> print(b)
b'auszuschließen…'
>>> b.decode()
'auszuschließen…'
>>> print(b.decode())
auszuschließen…
You start out with a Unicode string. Encoding it to ascii
creates a bytes
object with the characters you want. Python won't print it without converting it back into a string and the default conversion puts in the b
and quotes. Using decode
explicitly converts it back to a string; the default encoding is utf-8
, and since your bytes
only consist of ascii
which is a subset of utf-8
it is guaranteed to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With