开发者

Python Base64 print problem

I have a base64 encoded string

When I decode the string this way:

>>> import base64
>>> base64.b64decode("XH13fXM=")
'\\}w}s'

The output is fine.

But when i use it like this:

>>> d = base64.b64decode("XH13fXM=")
>>> pri开发者_如何学Pythonnt d
\}w}s

some characters are missing

Can anyone advise ?

Thank you in advanced.


It is just a matter of presentation:

>>> '\\}w}s'
'\\}w}s'
>>> print(_, len(_))
\}w}s 5

This string has 5 characters. When you use it in code you need to escape backslash, or use raw string literals:

>>> r'\}w}s'
'\\}w}s'
>>> r'\}w}s' == '\\}w}s'
True


When you print a string, the characters in the string are output. When the interactive shell shows you the value of your last statement, it prints the __repr__ of the string, not the string itself. That's why there are single-quotes around it, and your backslash has been escaped.

No characters are missing from your second example, those are the 5 characters in your string. The first example has had characters add to make the output a legal Python string literal.

If you want to use the print statement and have the output look like the first example, then use:

print repr(d)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜