开始Python -- String处理(1)

来源:互联网 发布:js 取消input选中 编辑:程序博客网 时间:2024/05/17 04:51

1、基本String操作

l         String支持大部分Sequence操作,但String是不可变的,所以所有Sequence赋值操作是不支持的:

>>> website = 'http://www.python.org'

>>> website[-3:] = 'com'

Traceback (most recent call last):

  File "<interactive input>", line 1, in ?

TypeError: object doesn't support slice assignment

 

2String格式化:简短形式

l         String的格式化操作符是“%”,左边是要格式化的String,右边是要格式化的值,可以是单值或Tuple或后面讲述的Dictionary(多值):

>>> format = "Hello, %s. %s enough for ya?"

>>> values = ('world', 'Hot')

>>> print format % values

Hello, world. Hot enough for ya?

l         格式化String中的%后的字符指定转换类型,见下面的表格:

转换类型

说明

d,i

有符号十进制整数

o

无符号八进制数

u

无符号整数

x

无符号十六进制数(小写)

X

无符号十六进制数(大写)

e

指数型浮点数(小写)

E

指数型浮点数(大写)

f,F

浮点数

g

根据精度显示普通浮点数还是指数型浮点数(小写)

G

根据精度显示普通浮点数还是指数型浮点数(大写)

c

字符(接受整数或单个字符的String

r

String(使用repr()转换)

s

String(使用str()转换)

l         在格式化String中使用%时,可以用%%替代

 

3、模版String

l         string模块提供了另一种格式化值的方法:模版String

>>> from string import Template

>>> s = Template('$x, glorious $x!')

>>> s.substitute(x='slurm')

'slurm, glorious slurm!'

l         如果替换的域是单词的一部分,需要用“{}”来区分:

>>> s = Template("It's ${x}tastic!")

>>> s.substitute(x='slurm')

"It's slurmtastic!"

l         在格式化String使用$,可以用$$替代

l         替代多key参数的方法就是使用key/value对的Dictionary

>>> s = Template('A $thing must never $action.')

>>> d = {}

>>> d['thing'] = 'gentleman'

>>> d['action'] = 'show his socks'

>>> s.substitute(d)

'A gentleman must never show his socks.'

l         Template提供了safe_substitute()方法,在缺少格式化值,或用法错误时,会忽略而不进行转换,不会抛异常

 

4String格式化:长形式

1) 宽度和精度

l         宽度:为格式化值保留的最小字符长度

l         精度:对数字,是精度位数;对String,是最大的字符长度

l         宽度和精度是两个整数,用“.”分割:

>>> from math import pi

>>> '%10f' % pi # Field width 10

' 3.141593'

>>> '%10.2f' % pi # Field width 10, precision 2

' 3.14'

>>> '%.2f' % pi # Precision 2

'3.14'

>>> '%.5s' % 'Guido van Rossum'

'Guido'

l         可以使用“*”来替代宽度或精度,以便从Tuple中读取:

>>> '%*.*f' % (10, 2, pi)

'      3.14'

2) 符号、对齐和前导零

l         0”表示前导零:

>>> '%010.2f' % pi

'0000003.14'

l         -”表示左对齐(缺省是右对齐)

>>> '%-10.2f' % pi

'3.14 '

l         空格表示保留符号位:

>>> print ('% 5d' % 10) + '/n' + ('% 5d' % -10)

 10

-10

l         “+”表示显示符号位:

>>> print ('%+5d' % 10) + '/n' + ('%+5d' % -10)

+10

-10

 

 
原创粉丝点击