[关闭]
@wangwangheng 2015-04-01T16:15:23.000000Z 字数 1579 阅读 2289

Python字符串和编码

其它编程语言


1. 常用编码:

2. Python中的字符串

    >>> chr(65)
    'A'
    >>> ord('B')
    66
    >>>
>>> u"张三"
u'\u5f20\u4e09'
>>> print u"张三"
张三
>>> print u"\u5f20\u4e09"
张三
>>> print "\u5f20\u4e09"
\u5f20\u4e09
    >>> u"ABC".encode("UTF-8")
    'ABC'
    >>> u"中文".encode("UTF-8")
    '\xe4\xb8\xad\xe6\x96\x87'
    >>> "abc".decode("UTF-8")
    u'abc'
    >>> "\xe4\xb8\xad\xe6\x96\x87".decode("UTF=8")
    u'\u4e2d\u6587'
>>> len("ABC")
3
>>> len(u"ABC")
3
>>> len("中文")
4
>>> len(u"中文")
2

第一行上是为告诉Linux/OS X系统, 这是一个Python可执行程序,Windows系统会忽略这个注释

第二行注释是为了告诉Python解释器,按照UTF-8的编码读取源代码,否则你在原代码中写的中文输出可能会有乱码

3. 字符串的格式化

Python的格式化字符串和C语言的一致,有多少个占位符,就要有多少个变量或者常量来替换这些占位符: 使用格式:`"占位符1,占位符2,占位符3" % (替换值1,替换值2,替换值3)`

%s 表示字符串
%d 表示整数
%f 表示浮点数
%x 表示十六进制整数

使用实例:
>>> "%2d - %2d" % (3,1)
' 3 -  1'
>>> "%.2f" % 3.1415926
'3.14'
>>> "name is %s" % ("张三")
'name is \xd5\xc5\xc8\xfd'
>>> "name is %s" % (u"张三")
u'name is \u5f20\u4e09'
>>> "Age :% s,Gender:%s" % (25,True)
'Age :25,Gender:True'
>>> u"name is %s" % (u"张三")
u'name is \u5f20\u4e09'
>>> "growth rate: %d %%" % 7
'growth rate: 7 %'

注意,在Python 3中,u"xxx"和""表示的一生一世是一致的,默认是Unicode编码,如果需要使用字节形式表示字符串,需要在字符串前面加上字符b:b"呵呵"

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注