码迷,mamicode.com
首页 > 其他好文 > 详细

对字符串和编码的处理方式

时间:2015-03-16 22:55:04      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:

1. 对编码主要是对中文的处理上:

一般我们处理含有中文的Python代码时:

1 #!/user/bin/env python  #针对Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释
2 #-*- coding: utf-8 -*-

2.字符串格式化的处理:

Python的格式化字符串类似于C语言的格式化%。

%用来格式化字符串的。

在字符串内部:

%s用来格式化字符串的

EX:

>>> "Hello, %s" % "world"
‘Hello, world‘
>>>

%d用来格式化整数的

%f用来格式化浮点数的

Note:格式化整数和浮点数还可以指定是否补0和整数与小数的位数.

 1 >>> ‘%02d‘%3
 2 ‘03‘
 3 >>> ‘%05d‘%3
 4 ‘00003‘
 5 >>> ‘%2d - %05d‘% (3,1)
 6 ‘ 3 - 00001‘ #3前面有一个空格
 7 >>>
 8 
 9 >>> ‘%.2f‘ % 3.1415926
10 ‘3.14‘
11 >>> ‘%0.2f‘ % 3.1415926
12 ‘3.14‘

%x用来格式化16进制的

1 >>> ‘%x‘ % 8
2 ‘8‘
3 >>> ‘%x‘ % 11
4 ‘b‘
5 >>>

当我们不知道该用什么是,%s永远起作用,它把任何数据类型转化为字符串

1 >>> ‘Age: %s. Gender: %s‘ % (25, True)
2 ‘Age: 25. Gender: True‘

对于Unicode字符串,我们最好确保替换的字符串也是Unicode字符串

1 >>> u‘Hello, %s‘ % u"孙先生"
2 u‘Hello, \u5b59\u5148\u751f‘
3 >>> print u‘Hello, %s‘ % u"孙先生"
4 Hello, 孙先生

对字符串中含有%时,需要用%%转义

1 >>> ‘The growth rate is: %s%%‘ % 7
2 ‘The growth rate is: 7%‘
3 >>> ‘The growth rate is: %s %‘ % 7
4 Traceback (most recent call last):
5   File "<stdin>", line 1, in <module>
6 ValueError: incomplete format
7 >>>

 

对字符串和编码的处理方式

标签:

原文地址:http://www.cnblogs.com/sunjzcoding/p/4342951.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!