How can I print the raw unicode in python?
Asked Answered
C

2

7

I am novice in Python, so maybe I can't express it well...

I got a string '\xb9\xfe'

I want it print in this very fashion '\xb9\xfe', not converting to a Chinese character '哈'.

What is the proper way to do it?

Cookery answered 26/7, 2014 at 19:7 Comment(0)
C
5

Use a raw string literal instead:

r'\xb9\xfe'

or print the output of repr() of your string:

print(repr('\xb9\xfe'))
Committeeman answered 26/7, 2014 at 19:8 Comment(4)
Won't that raw string be '\' 'x' 'b' '9' '\' 'x' 'f' 'e'?Jeth
@mpez0: yes, it will be. It's not clear which variant the OP really wanted here; storing the value with 8 characters or only producing that value when printing.Committeeman
Why doesn't this work then? >>> a = 'asdf\u0642\u064f\u0644\u0652' >>> a 'asdfقُلْ' >>> repr(a) "'asdfقُلْ'"Kalpa
@Tjorriemorrie: because in Python 3 you'd want to use ascii() instead of repr() if you want non-ASCII printable characters to be represented as escape sequences.Committeeman
S
2

The correct answer is by using s.encode('unicode_escape').decode()

s = "asdf\u0642\u064f\u0644\u0652"
print(s.encode('unicode_escape').decode())

Output will be:

asdf\u0642\u064f\u0644\u0652

This will NOT work:

s = "asdf\u0642\u064f\u0644\u0652"
print(s)
print(repr(s))

Output will be:

asdfقُلْ
'asdfقُلْ'
Sidonnie answered 28/3, 2023 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.