python中unicode字符串的转换 [英] conversion of unicode string in python

查看:60
本文介绍了python中unicode字符串的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 Python 中的 unicode 字符串转换为其他类型,例如无符号和有符号 int 8 位、无符号和有符号 int 16 位、无符号和有符号 int 32 位、无符号和有符号 int 64 位、double、float、string,无符号和有符号 8 位,无符号和有符号 16 位,无符号和有符号 32 位,无符号和有符号 64 位.

I need to convert unicode strings in Python to other types such as unsigned and signed int 8 bits,unsigned and signed int 16 bits,unsigned and signed int 32 bits,unsigned and signed int 64 bits,double,float,string,unsigned and signed 8 bit,unsigned and signed 16 bit, unsigned and signed 32 bit,unsigned and signed 64 bit.

我需要你们的帮助.

推荐答案

use int() 将字符串转换为整数.Python 没有不同的固定宽度整数,所以你只会得到一种类型的东西.

use int() to convert the string to an integer. Python doesn't have different fixed-width integers so you'll just get one type of thing out.

然后使用 struct 将整数打包成一个固定宽度:

Then use struct to pack the integer into a fixed width:

res = struct.pack("=B",i) ## uint8_t
res = struct.pack("=b",i) ## int8_t

res = struct.pack("=H",i) ## uint16_t
res = struct.pack("=h",i) ## int16_t

res = struct.pack("=I",i) ## uint32_t
res = struct.pack("=i",i) ## int32_t

res = struct.pack("=Q",i) ## uint64_t
res = struct.pack("=q",i) ## int64_t

res = struct.pack("=f",i) ## float
res = struct.pack("=d",i) ## double

struct 产生一个包含二进制数字的字节串.

struct produces a byte-string containing the number in binary.

从评论来看,您似乎只想将字符串(十进制数字)转换为整数.只需使用 int() 即可,但是您不会获得指定类型的所有复杂上溢/下溢语义.您无法在 Python 中重现它,至少在不编写大量代码的情况下无法重现.

From the comments it sounds like you just want to convert the string (of decimal digits) into an integer. Just use int() for that, however you won't get all the complicated overflow/underflow semantics of the specified types. You can't reproduce that in python, at least not without writing a whole lot of code.

我认为,如果您需要更多帮助,则必须更准确地了解您想要实现的目标.

I think if you want any more help you'll have to be more precise about what you want to achieve.

这篇关于python中unicode字符串的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆