1. > 智能数码 >

pythonobject转string success

python3 对象 |字典|json|yaml|字符串 相互转化

在研究 k8s 的yaml 配置文件的时候,我总担心自己一不小心 会写错,所以我向往 使用将对象 序列化 yaml 的形式,

其实 python object 可以 直接 转 yaml ,甚至也可以 直接 转成yaml文件!!!

这里 会经常用到几个 函数 vars() ast.

我们先尝试用最笨的方法 实现 object到yaml 的转化

在python对象 convert to dict 的形式,使用 vars()函数

然后 dict convert to json 使用 json.dumps(dict)函数

然后 json converte to yaml 使用 ya= yaml.load(json.dumps(dict)) 然后

再 yaml.safe_dump(ya,default_flow_style=False)

至此我们看到 从 python Object ---> dict ----> json ---> yaml 的转化

其中 obj dict json yaml 转 string ,只要 str()函数即可,或者 str(vars())结合

yaml 格式 写入到文件 ,需要注意的是, open()函数 的mode 一定要是 'w' ,不能是’wb', b代表是二进制写入

yaml 写入的是dict str,使用 ‘wb' 会报错,[yaml TypeError: a bytes-like object is required, not 'str']

【出现该错误往往是通过open()函数打开文本文件时,使用了‘rb’属性,如:fileHandle=open(filename,'rb'),则此时是通过二进制方式打开文件的,所以在后面处理时如果使用了str()函数,就会出现该错误,该错误不会再python2中出现。

具体解决方法有以下两种:

第一种,在open()函数中使用‘r’属性,即文本方式读取,而不是‘rb’,以二进制文件方式读取,可以直接解决问题。

第二种,在open()函数中使用‘rb’,可以在使用之前进行转换,有以下实例,来自: 】

其实 python object 可以 直接 转 yaml ,甚至也可以 直接 转成yaml文件!!!

比如我已经定义了一个 Dog python class,他有 好几个属性 并已经赋值初始化了

另外生成 yaml 对象

生成yaml文件

结果是

反过来 yaml ----> json ---> 持久化 json 文件 indent=1属性是为了让 json 不以单行展示,而是展开

注意的是 python 的 dict 和set 很相似 ,都是 { }, set 里是list, dict 是键值对

【# set object is not JSON serializable [duplicate]

打开 demo.json

yaml ---> dict

yaml ---> python object

json --> dict

json.loads()

dict--> json

json.jumps()

str ---> dict

newdict=dict(str)

json -- > python object

一个python object无法直接与json转化,只能先将对象转化成dictionary,再转化成json;对json,也只能先转换成dictionary,再转化成object,通过实践,源码如下:

yaml --> python object

对yaml,也只能先转换成json --->dictionary,再转化成object,通过实践,源码如下:

dict -- ->python object

python对象 默认都有一个 私有的属性 dict 取值 就是 object的 字典形式, 赋值就就可以给对象属性对应赋值

例如json 转 对象

对象 转 json

Python之dict(或对象)与json之间的互相转化

在Python语言中,json数据与dict字典以及对象之间的转化,是必不可少的操作。

dict字典转json数据

对象转json数据

json数据转成dict字典

json数据转成对象

json的load()与dump()方法的使用

dump()方法的使用

python mongo 的objectid 怎么转化为string

MongoDB里的_id字段前四位是时间戳的16进制表示,通过Python可以很容易从_id中提取出时间戳来

def timestamp_from_objectid(objectid):

result = 0

try:

result = time.mktime(objectid.generation_time.timetuple())

except:

pass

return result

怎样将python中PyObject 类型转换成c++中string类型

使用ctypes包 这个包提供了python 与c语言交互的功能 可以使用 ctypes.c_char(str),来强制转换为c语言的char类型 类型的对比图附送

怎样将python中PyObject 类型转换成c++中string类型

使用PyString_AsString(pyobj)函数,从PyObject指针里面获取字符串指针。

注意,上面的函数不适用与Unicode字符串。Unicode 字符串请另行参考Python C API编程手册。

python怎么将objectid转为str

bson的话

比如,我的是MongoDB查询出的id

导入bson模块

for id in cursor:

id = id.get('_id',"空")

#此时的id类型为bson.objectid.ObjectId

id = id.__str__()

#此时的id类型为str

json的话

导入json模块

JSON的dumps()函数可以将python的各种数据类型转换为字符串,loads()函数可以将相应的字符串转换回python变量

Python String和PyQt QString的区别

以下在python2.5和PyQt4.4.6 for python2.5环境下讨论。

在python中有两种与字符有关的类型:string object和Unicode object。

平时进行输入输出的一般都用string

object,当需要显示一些特殊字符或者中文等文字时候,需要转换为Unicode编码。在PyQt中也有两种字符类型与上面两者对应:QByteArray和QString,主要是使用QString操作数据。

1) python string

object可以理解为一个接一个字节的字节组,至于表示什么编码,与表示文字有关,比如“python

string”,“中文”。注意它是有不同编码区分的。

PyQt中与之对应的是QbyteArray,而不是Qstring。

A built-in string object (plain or Unicode) is a sequence of

characters used to store and represent text-based information

(plain strings are also sometimes used to store and represent

arbitrary sequences of binary bytes). (摘自《Python in a

NutShell》)

QByteArray can be used to store both raw bytes (including '"0's)

and traditional 8-bit '"0'-terminated.(摘自《PyQt手册》)

2)Python Unicode

object可以理解为固定使用utf-16编码的字节组,其中英文和中文都使用两个字节(16位)来表示,如:u"Python

Unicode object"、u"中文"。

PyQt中与之对应的就是QString了。

Unicode string literals have the same syntax as other string

literals, with a u or U immediately before the leading quote.

(摘自《Python in a NutShell》)

Qt also provides the QString class to store string data. It stores

16-bit Unicode characters, making it easy to store

non-ASCII/non-Latin-1 characters in your

application.(摘自《PyQt手册》)

QString stores a string of 16-bit QChars, where each QChar

corresponds one Unicode 4.0 character.(摘自《PyQt手册》)

2 PyQt内部类型转换

QString有

toAscii()、toUtf8()函数转换为QByteArray类型,(这个基本不用,因为很少直接用QByteArray类型)有__init__

(self, QByteArray a)函数将QByteArray类型转为QString。

3. Python string object和Python Unicode object相互转换

1)Python string object是原始编码是有区分的,通过 decode('原始编码')

函数解码得到通用utf16编码即Python Unicode object。

>>>"python

string".decode('ascii')

或者

>>>"python

pythonobject转string successpythonobject转string success


string".decode()

得到 u"python string"

因为默认按ascii解码。

>>>"中文".decode('gbk')

pythonobject转string successpythonobject转string success


得到 u""u4e2d"u6587" ,打印出来就是 中文 二字。(注意结果是2字节一组,共两组,对应两个汉字)

又:"python string".decode('gkb') ,即按汉字来解码,也可以得到 u"python

string",因为gbk编码也支持英文字母;

但是"中文".decode('ascii') 即按ascii解码是错误的,因为ascii编码不支持汉字!

>>>

"dfdf".decode()

u'dfdf'

>>>

"dfdf".decode("ascii")

u'dfdf'

>>>

"dfdf".decode("gbk")

u'dfdf'

>>>

"中文".decode("gbk")

u'"u4e2d"u6587'

>>>print

"中文".decode("gbk")

中文

>>>

"中文".decode("gb2312")

u'"u4e2d"u6587'

>>>

"中文".decode("ascii")

Traceback (most recent call last):

File "", line 1,

in

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd6 in

position 0: ordinal not in range(128)

2)Python Unicode object原始编码固定是utf16,通过 encode('目的编码') 编码来得到Python

string object。

>>>u"unicode

string".encode()

或者

>>>u"unicode

string".encode('ascii')

得到

'unicode string',默认目的编码为ascii。

>>>u"中文".encode("gbk")

得到'"xd4"xd0"xce"xc4',打印出来就是 中文。(注意结果是1字节一组,共4组)

>>>

u"sdff".encode()

'sdff'

>>>

u"sdff".encode('ascii')

'sdff'

>>>

u"sdff".encode('gbk')

'sdff'

>>>

u"sdff".encode('gb2312')

'sdff'

>>>

u"中文".encode('gbk')

'"xd6"xd0"xce"xc4'

>>> print

u"中文".encode('gbk')

中文

>>>

u"中文".encode('ascii')

Traceback (most recent call last):

File "", line 1, in

UnicodeEncodeError: 'ascii' codec can't encode characters in

position 0-1: ordin

al not in range(128)

注意:执行>>>

u"中文".encode('gbk')命令需要你的IDE支持gbk编码,在官方shell下执行肯定没问题,但如果你的IDE比如PyWin中文输入异常,则可能报错。

4. Python string object和Python Unicode object向QString的转换。

Qt一般不直接操作QByteArray,只需关注Python string object和Python Unicode

object向QString的转换。

很多关于PyQt4的英文书籍说:PyQt函数需要QString参数的地方都可以直接用Python string

pythonobject转string successpythonobject转string success


object或者Python Unicode object,如果非要转换可以直接用QtCore.QString()构造。比如《GUI

Programming with PyQt》,再如《PyQt手册》:

Whenever PyQt expects a QString as a function argument, a Python

string object or a Python Unicode object can be provided instead,

and PyQt will do the necessary conversion automatically.

You may also manually convert Python string and Unicode objects to

QString instances by using the QString constructor as demonstrated

in the following code fragment:

qs1 = QtCore.QString("Converted Python string object")

qs2 = QtCore.QString(u"Converted Python Unicode object")

但可惜这只适用于英文即ascii编码,对于中文则行不通!

直接的QString:

>>>

QtCore.QString('中文')

PyQt4.QtCore.QString(u'"xd6"xd0"xce"xc4')

>>> print

QtCore.QString('中文')

Traceback (most recent call last):

File "", line 1, in

UnicodeEncodeError: 'ascii' codec can't encode characters in

position 0-3: ordin

al not in range(128)

>>>

>>>

QtCore.QString(u'中文')

PyQt4.QtCore.QString(u'"u4e2d"u6587')

>>> print

QtCore.QString(u'中文')

Traceback (most recent call last):

File "", line 1, in

UnicodeEncodeError: 'ascii' codec can't encode characters in

position 0-1: ordin

al not in range(128)

>>>

因为它们都是默认按ascii编码转换!

GUI编程:

可以创建一个QTextEdit对象myTextEdit, 检验:

myTextEdit.append("中文")

或者

myTextEdit.append(u"中文")

或者

myTextEdit.append(QtCore.QString('中文'))

或者

myTextEdit.append(QtCore.QString(u'中文'))

你会发现显示都是乱码...因为它们都是默认按ascii编码进行内部转换得到QString相应utf16编码的。

解决方法是:

利用unicode()函数显示指定gb2312编码进行中文编码转换,转换后的Python Unicode

object则是可以直接作为QString参数代入用的:

>>> unicode('中文',

'gb2312', 'ignore')

u'"u4e2d"u6587'

>>> print

unicode('中文', 'gb2312', 'ignore')

中文

>>>

myTextEdit.append(unicode('中文', 'gb2312', 'ignore'))

#用以替代myTextEdit.append(u"中文")

或者多此一举下:

myTextEdit.append(QtCore.QString(unicode('中文', 'gb2312',

'ignore')))

#用以替代myTextEdit.append(QtCore.QString(u'中文'))

5. QString向Python string object和Python Unicode object的转换。

Python中需要用Python string object和Python Unicode

object的地方可就不一定可以直接用QString了!!!

QString向Python string object转换可以理解,因为编码不同。

QString向Python Unicode object的转换?需要转换吗?不都是utf16编码吗?

QString是tuf16编码,但是它的实现并非Python Unicode

object那样直接的utf16码,而实际是一个QChar串,每个QChar才对应unicode符,所以地位相当但并不相同。

许多英文书籍写到:可以使用str()函数直接将QString转换为Python string

object,可以使用unicode()直接将QString转换为Python Unicode

object。如《PyQt手册》:

In order to convert a QString to a Python string object use the

Python str() builtin. Applying str() to a null QString and an empty

QString both result in an empty Python string object.

In order to convert a QString to a Python Unicode object use the

Python unicode() builtin. Applying unicode() to a null QString and

an empty QString both result in an empty Python Unicode

object.

但同样只适用于英文,具体见下面分别分析。

1)QString向Python Unicode object的转换。

>>> from PyQt4 import

QtGui, QtCore

>>>

unicode(QtCore.QString('def'))

u'def'

>>> print

unicode(QtCore.QString('def'))

def

对于中文,unicode()必须要指定编码后有效。(这样也只针对直接的QString有效?对于Qt

GUI编程中,从QWidget取得的QString无效?)

>>> from PyQt4 import

QtGui, QtCore

>>>

unicode(QtCore.QString('中文'))

u'"xd6"xd0"xce"xc4'

>>> print

unicode(QtCore.QString('中文'))

Traceback (most recent call last):

File "", line 1, in

UnicodeEncodeError: 'gbk' codec can't encode character u'"xd6' in

position 0: il

legal multibyte sequence

指定原始编码后:

>>>

unicode(QtCore.QString('中文'),'gbk','ignore')

u'"u4e2d"u6587'

>>> print

unicode(QtCore.QString('中文'),'gbk','ignore')

中文 TEST

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, website.service08@gmail.com 举报,一经查实,本站将立刻删除。

联系我们

工作日:9:30-18:30,节假日休息