python string和PyQt的QString的区别 以下在Python2.6和PyQt4.4.4 for Python2,6环境下讨论: Python中有两种有关字符的类型:Python string object和Python Unicode object。主要使用Python string object进行数据输入

python string和PyQt的QString的区别

以下在 Python2.6和PyQt4.4.4 for Python2,6环境下讨论:

Python中有两种有关字符的类型:Python string object和Python Unicode object。主要使用Python string object进行数据输入输出。

PyQt中与之相对应的字符有关类型是:QByteArray和QString。主要使用QString操作数据。

1. Python和PyQt中的类型对应

注意是类型相似,不是相等。

需要先了解编码:ascii、gb2312、big5,这些是各国自己文字不同的编码;unicode,国际通用编码,就是穷尽这个世界上所有的文字,给

每个文字编一个,又分utf-8方案--最常使用的128个英文字母用一个字节来表示,而中文使用三个字节来表示,utf-16方案--其中英文和中文都

使用两个字节来表示,而其它字符采用四个字节,utf-32方案--所有的文字都用四个字节来表示。

unicode就可用来作为各种独立编码如ascii、gb2312、big5的转换中介。

Python中gkb == gb2312。

1)Python string object可以理解为一个接一个字节(byte,8位)的字节组,至于表示什么编码,与表示文字有关,如:"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 string".decode()

得到 u"python string"

因为默认按ascii解码。

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

得到 u"u4e2du6587" ,打印出来就是 中文 二字。(注意结果是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'u4e2du6587'

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

中文

>>> "中文".decode("gb2312")

u'u4e2du6587'

>>> "中文".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")

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

>>> u"sdff".encode()

'sdff'

>>> u"sdff".encode('ascii')

'sdff'

>>> u"sdff".encode('gbk')

'sdff'

>>> u"sdff".encode('gb2312')

'sdff'

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

'xd6xd0xcexc4'

>>> 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 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'xd6xd0xcexc4')

>>> 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'u4e2du6587')

>>> 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'u4e2du6587'

>>> 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'xd6xd0xcexc4'

>>> 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'u4e2du6587'

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

中文

>>>

GUI编程中:

但这种方法在GUI编程中似乎无效?

比如创建一个QLineEdit对象myLineEdit,写入汉字,则:

myText = unicode(self.myLineEdit.text(),'gb2312','ignore')

myText = unicode(QtCore.QString(self.myLineEdit.text()),'gb2312','ignore')

print myText都是乱码.

尝试将 unicode()的参数改为QByteArray,但QString没有toGbk()或toGb2312()函数,只有toUtf8()和 toAsciii()函数,利用下试试:

myText = unicode(self.myLineEdit.text().toUtf8(),'utf8', 'ignore')

myText = unicode(self.myLineEdit.text().toAscii(),'ascii', 'ignore')

因为不是gbk编码,所以打印都还是乱码。

过python中一 般从文件、终端、网络数据流或者其它外部输入中读取的都是Python string

object类型,而且向文件、终端、网络也只能输出Python string

object类型。所以这个问题可以跳过,通过下面讲的内容,发现可以在此基础上转为Python string object使用。

2)QString向 Python string object的转换。

A. 第一种方法:

可以直接借助上一步得到的Python Unicode object和encode()函数获得Python string object。

>>> unicode(QtCore.QString('dfd')).encode('gb2312')

'dfd'

>>> unicode(QtCore.QString('dfd')).encode('ascii')

'dfd'

>>>

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

'xd6xd0xcexc4'

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

中文

>>>

B. 第二种方法:

也可利用str():

>>> str(QtCore.QString('def'))

'def'

>>> print str(QtCore.QString('def'))

def

>>>

但是对于中文,直接调 用str()是无效的!

>>> str(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)

对于str()函数默认以ascii编码转换,而str()函数又只能接受一个参数,改不了别的编码,所以对汉字自然不行。

先用unicode()指定gb2312解码再利用str()呢?:

>>> str(unicode(QtCore.QString('中文'), 'gb2312', 'ignore'))

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)

还是----str()函数默认以ascii编码转换!

C. 对于中文考虑第一种方法:

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

'xd6xd0xcexc4'

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

'xd6xd0xcexc4'

>>> print unicode(QtCore.QString('中文'),'gbk','ignore').encode('gb2312')

中文

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

中文

>>>

GUI编程中:

但是对于前面myLineEdit的情况怎么处理呢?

myText = unicode(self.myLineEdit.text(),'gb2312','ignore')是乱码,encode('gb2312')之后 呢?

myText = unicode(self.myLineEdit.text(),'gb2312','ignore').encode('gb2312')

打印依然是乱码!?

后面尝试将unicode()的参数改为QByteArray、利用QString的toUtf8()得到的虽然不是gbk编码,但是进一步 encode('gb2312')又如何呢:

myText = unicode(self.myLineEdit.text().toUtf8(),'utf8', 'ignore').encode('gb2312')

发现print myText显示正常!!!:

中文

且python方式打开文件后查找该字符串也正常,证明myText是转换成功的Python string object!!!

注意:1)借助 toAscii()函数(除了toUtf8只有这个...)不行?!

myText = unicode(self.myLineEdit.text().toAscii(),'ascii', 'ignore').encode('gb2312')

打印是乱码。

难道PyQt的Ascii和Python的ascii不一样?

2)这种借助utf8码的方式对于直接的QString反而不行!?

>>> unicode(QtCore.QString('中文').toUtf8(),'utf8','ignore').encode('gb2312')

Traceback (most recent call last):

File "", line 1, in

UnicodeEncodeError: 'gb2312' codec can't encode character u'xd6' in position 0:

illegal multibyte sequence

>>> unicode(QtCore.QString('中文 ').toAscii(),'ascii','ignore').encode('gb2312')

''

>>> print unicode(QtCore.QString('中文').toAscii(),'ascii','ignore').encode('gb2

312')

>>>

D. 对于中文考虑第二种方法:

利用QString的toAscii()函数后再使用str()函数:

>>> str(QtCore.QString('中文').toAscii())

'xd6xd0xcexc4'

>>> print str(QtCore.QString('中文').toAscii())

中文

>>>

str(QtCore.QString('中文').toAscii())得到的是ascii编码?尝试将其转为unicode?

>>> unicode(str(QtCore.QString('中文').toAscii())).encode('gbk')

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)

>>> unicode(str(QtCore.QString('中文').toAscii()),'ascii').encode('gbk')

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)

>>> unicode(str(QtCore.QString('中文 ').toAscii()),'ascii','ignore').encode('gbk'

)

''

>>>

>>> unicode(str(QtCore.QString('中文').toAscii()))

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)

难道PyQt的Ascii和Python的ascii不一样?

GUI编程中:

myText = str(self.myLineEdit.text().toAscii())

打印发现还是乱码!?

myText = unicode(str(self.myLineEdit.text().toAscii())).encode('gb2312')

打印发现还是乱码!?

6. 总结:

1)Python string object是原始编码是有区分的,通过 decode('原始编码') 解码得到utf16类型即Python

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

编码来得到Python string object。

2)

对于英 文,PyQt函数需要QString参数的地方都可以直接用Python string object或者Python Unicode

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

object可以直接作为QString参数代入。

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

3)

对于英文,可以使 用unicode()直接将QString转换为Python Unicode

object,并进一步encode()得到Python string

object,也可以使用str()函数直接将QString转换为Python string

object。对于中文,利用unicode()指定原始编码gbk来解决QString转换为Python Unicode

object问题,但对于GUI使用仍有缺陷,不过无碍;进一步利用encode('gb2

312')得到Python string object,或者结合QString的toUtf8()再利用str()函数;但对于GUI编程str()方法还是不行,只可结合QString的 toUtf8()进行unicode()转换后再利用encode('gb2

312')。

str(QtCore.QString(' 中文').toAscii())

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

myText = unicode(self.myLineEdit.text().toUtf8(),'utf8', 'ignore').encode('gb2312')

7. 中文?为什么不用类似C++中Qt的方法解决上面中文的使用?

C++中Qt一般是利用tr()方法翻译(便于国际化),或者简单设置:

QTextCodec::setCodecForTr(QTextCodec::codecForName("GB2312"));

QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));

QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB2312"));

1)前者PyQt4中对应是QCoreApplication.translate(),比如pyuic4自动生成的.py文件中可以看到:

def retranslateUi(self, mainWindow):

mainWindow.setWindowTitle(QtGui.QApplication.translate("mainWindow", "名称", None, QtGui.QApplication.UnicodeUTF8))

QtGui.QApplication.UnicodeUTF8继承自QCoreApplication的

enum Encoding { CodecForTr, UnicodeUTF8, DefaultCodec }

但这需保证写入的汉字是UnicodeUTF8编码,比如前面myLineEdit读入的ini文件中汉字就需用utf8表示?CodecForTr是使

用QTextCodec.codecForTr() (Latin-1 if none has been

set).但后面可看到PyQt4中无code包?

PyQt4手册说明如下:

Unfortunately, because of the way Qt implements tr() (and trUtf8())

it is not possible for PyQt to exactly reproduce its behaviour. The PyQt

implementation of tr() (and trUtf8()) uses the class name of the

instance as the context. The key difference, and the source of potential

problems, is that the context is determined dynamically in PyQt, but is

hardcoded in Qt. In other words, the context of a translation may

change depending on an instance's class hierarchy.

The PyQt behaviour is unsatisfactory and may be changed in the future.

It is recommended that QCoreApplication.translate() be used in

preference to tr() (and trUtf8()). This is guaranteed to work with

current and future versions of PyQt and makes it much easier to share

message files between Python and C++ code. Below is the alternative

implementation of A that uses QCoreApplication.translate():

class A(QtCore.QObject):

def hello(self):

return QtCore.QCoreApplication.translate("A", "Hello")

2) 但后者方法在PyQt中未能成功:

QtCore.QTextCodec.setCodecForTr(QtCore.QTextCodec.codecForName("gb2312"))

QtCore.QTextCodec.setCodecForCStrings(QtCore.QTextCodec.codecForName("gb2312"))

QtCore.QTextCodec.setCodecForLocale(QtCore.QTextCodec.codecForName("gb2312"))

后证实PyQt4中无code包?ascii也没有?...

if not QtCore.QTextCodec.codecForName("gb2312"):

print 'no code'

python3怎么使用qstring_PyQt的QString和python的string的区别相关推荐

  1. python3怎么使用qstring_请问PyQt的QString和python的string的区别?

    以下在python2.5和PyQt4.4.6 for python2.5环境下讨论. 在python中有两种与字符有关的类型:string object和Unicode object. 平时进行输入输 ...

  2. python3中format函数 出现keyerror_关于python:string.Formatter抛出KeyError”

    我想像这个问题一样打印出键+值对, key a:         1 key ab:        2 key abc:       3 ^ this colon is what I want 但是我 ...

  3. centos7 python3.6升级到3.7_Centos7下把python 2.7升级到python 3.6(升级过程遇到的一些相关问题)...

    Centos 7 默认安装的Python 的版本是2.7的,现在不少人用的是3.x上的版本,故而需要了解下如何从Python2.7升级到Python 3.6. 在虚拟机安装时,网络不通会先遇到一个错误 ...

  4. python2和python3如何共存,如何安装多版本python python2和python3共存以及pip共存

    Python的版本是挺折腾人的,本着简单实用的原则我介绍一下我是如何安装多版本Python的. 环境:windows10(64位) Python版本:2.7.13和3.5.2 1.安装Python2. ...

  5. Python3安装turtle提示错误:Command python setup.py egg_info failed with error code 1

    Python3安装turtle提示错误:Command "python setup.py egg_info" failed with error code 1 Python3.5安 ...

  6. python3哪个版本稳定-不要再纠结Python哪个版本好,2020年用Python3就对了

    2020年用Python3就对了!Python 3比Python 2慢吗?哪一个版本的Python 3最快?不要再纠结Python哪个版本好!还有什么其他措施可以提高速度?哪个版本的Python最快? ...

  7. 【Python3零基础入门笔记】05 Python时间处理——time库的使用

    time库的使用: time库基本情况 时间获取 时间格式化 程序计时 文本进度条实例 time库基本情况 Time库是python中处理时间的标准库 计算机时间表达 提供获取系统时间并格式化输出功能 ...

  8. Python 2.x 与 Python 3.x 的区别

    前言 如果你是刚接触 Python 的初学者,那你可能是直接学习 Python 3.x 版本.对于 Python 2.x 的版本是不会有所接触.官方也宣布在 2020 停止对 Python 2.x 的 ...

  9. python学习-综合练习三(斐波那契数列、阿姆斯特朗数、//和/、十进制转二进制bin、八进制oct、十六进制hex、进制转换源码、python中::和:的区别)

    文章目录 斐波那契数列 阿姆斯特朗数 十进制转二进制bin.八进制oct.十六进制hex 补充进制转换源码 python中::和:的区别 说明:本篇博文的知识点大部分来自 Python3 实例 斐波那 ...

最新文章

  1. Oracle中table的大小计算方式
  2. Random:产生随机数的类
  3. Vue开发中遇到的问题及解决方案
  4. [na]vrrp两用(网关冗余+服务器热备)
  5. 最常用计算机信息呼唤标准代码,计算机考试题
  6. 前端学习(1221):使用过滤器格式化日期
  7. 7-1:C++的IO流
  8. ThinkPHP导出CSV、Excel
  9. lanmp_wdcp_v2.4快速安装RPM包发布
  10. java调用ant工具
  11. 应用:Xbox 360无线大屏幕控制器“WP 7”
  12. TextWatcher基本用法
  13. 解决No instances available for XXX
  14. onblur 与onclick 冲突;onblur导致onclick事件丢失
  15. 地图坐标转换问题--百度地图定位偏
  16. 二级c语言百度云,全国计算机二级C语言历年真题完整版.pdf
  17. 商户注册和资质申请的业务流程
  18. 18. 图像分类、分割
  19. 你相信进化吗?探索通用人工智能的重要途径 | 算法观点
  20. python拼多多领现金_拼多多领现金100元攻略 100元快速提现技巧

热门文章

  1. tensorflow实现LeNet-5模型
  2. 程序员面试金典——11.3元素查找
  3. 【有返回值的回溯】剑指offer——面试题67——机器人的运动范围(回溯法)
  4. 借教室(codevs 1217)
  5. Struts入门学习(三)---自定义类型转换器
  6. [家里蹲大学数学杂志]第275期华中师范大学2011年数学专业复试试题及部分参考解答...
  7. 图片尺寸判断等-我们到底能走多远系列(21)
  8. ABAP--动态创建类型和变量的使用程序样例
  9. Linux 基金会成立持续交付基金会
  10. POSTMAN list参数传值