字符串转换 python
String Conversion python
我有一个关于 python3 中字符串转换的小问题。
s = '\x001\x002\x001\x000\x005\x005\x000\x004\x000\x000\x00'
print(s) -> 给出输出:
1 2 1 0 5 5 0 4 0 0
但是,当我尝试使用以下方法转换字符串时:
bytes(s, 'utf16').decode('utf16')
,我得到'\x001\x002\x001\x000\x005\x005\x000\x004\x000\x000\x00'。
以编程方式获得与打印相同的输出的方法是什么?
你只需要解码这个二进制文件,你就会得到答案
x = b'\x001\x002\x001\x000\x005\x005\x000\x004\x000\x000\x00'
str1 = x.decode('utf-8')
print(" ".join([i for i in str1 if ord(i) != 0]))
第二个解决方案:
x = '1 2 1 0 5 5 0 4 0 0'
str_utf32 = x.encode('utf16')
print("Encoding :",str_utf32)
print("Decoding :",str_utf32.decode('utf16'))
输出
Encoding : b'\xff\xfe1\x00 \x002\x00 \x001\x00 \x000\x00 \x005\x00 \x005\x00 \x000\x00 \x004\x00 \x000\x00 \x000\x00'
Decoding : 1 2 1 0 5 5 0 4 0 0
在第一个示例中,您打印字符串 s
,控制台将忽略 \x00
。你做一个 print(s)
.
在你的最后一行,你从 python 提示中得到了字符串。如果你打印它:print(bytes(s,'utf-16').decode('utf-16'))
,你得到你想要的。
所以 Python 提示向您展示了带有上下文的变量(例如,您还看到了 '
标志),但不是字符串的真实表示形式(print
).
附录:
print
将在其参数中打印字符串,最终调用 str()
将参数转换为字符串。但是 python 提示将打印变量的表示(由 repr()
给出)。因此您可以 print(repr(bytes(s,'utf-16').decode('utf-16')))
获得与 python 交互式会话中相同的字符串,但作为字符串. 而不是打印,你可以分配这样的功能(r = repr(bytes(...).decode(...))
,所以你有 r[0]
是 '
,r[1]
是 \
,等等
我有一个关于 python3 中字符串转换的小问题。
s = '\x001\x002\x001\x000\x005\x005\x000\x004\x000\x000\x00'
print(s) -> 给出输出:
1 2 1 0 5 5 0 4 0 0
但是,当我尝试使用以下方法转换字符串时:
bytes(s, 'utf16').decode('utf16')
,我得到'\x001\x002\x001\x000\x005\x005\x000\x004\x000\x000\x00'。
以编程方式获得与打印相同的输出的方法是什么?
你只需要解码这个二进制文件,你就会得到答案
x = b'\x001\x002\x001\x000\x005\x005\x000\x004\x000\x000\x00'
str1 = x.decode('utf-8')
print(" ".join([i for i in str1 if ord(i) != 0]))
第二个解决方案:
x = '1 2 1 0 5 5 0 4 0 0'
str_utf32 = x.encode('utf16')
print("Encoding :",str_utf32)
print("Decoding :",str_utf32.decode('utf16'))
输出
Encoding : b'\xff\xfe1\x00 \x002\x00 \x001\x00 \x000\x00 \x005\x00 \x005\x00 \x000\x00 \x004\x00 \x000\x00 \x000\x00'
Decoding : 1 2 1 0 5 5 0 4 0 0
在第一个示例中,您打印字符串 s
,控制台将忽略 \x00
。你做一个 print(s)
.
在你的最后一行,你从 python 提示中得到了字符串。如果你打印它:print(bytes(s,'utf-16').decode('utf-16'))
,你得到你想要的。
所以 Python 提示向您展示了带有上下文的变量(例如,您还看到了 '
标志),但不是字符串的真实表示形式(print
).
附录:
print
将在其参数中打印字符串,最终调用 str()
将参数转换为字符串。但是 python 提示将打印变量的表示(由 repr()
给出)。因此您可以 print(repr(bytes(s,'utf-16').decode('utf-16')))
获得与 python 交互式会话中相同的字符串,但作为字符串. 而不是打印,你可以分配这样的功能(r = repr(bytes(...).decode(...))
,所以你有 r[0]
是 '
,r[1]
是 \
,等等