第03章: 使用字符串
------
支持的操作
>>> website='http://www.python.org' >>> website[-3:]='com' #此操作不合法,因为字符串是不变,不能做修改 Traceback (most recent call last): File "------", line 1, in website[-3:]='com' TypeError: 'str' object does not support item assignment
字符串格式化:
%s:转换说明符 元祖
#字符型 >>> str1 = "Hello, %s. %s enough for you ya?" >>> val1 = ('Jerry','Hot') >>> print str1 % val1 Hello, Jerry. Hot enough for you ya? #浮点型 >>> format = "PI with three decimals: %.3f" >>> from math import pi >>> print format % pi PI with three decimals: 3.142 Note: 1. 使用列表的话,序列会理解成一个值,只有元祖和字典可以格式化一个以上的值 2. 百分号: %% 模板字符串 #类似于linux中的变量替换,Template,substitute(将传的参数进行转换) >>> s = Template('$x,glorious $x!') >>> s.substitute(x='slurm') 'slurm,glorious slurm!' #如果是单词的一部分的话,用{}括起来 >>> s = Template('I love ${x}rry!') >>> s.substitute(x='She') 'I love Sherry!' #如果是美元, 注意用$$来表示美元符,safe_substitute不会因缺少值或美元符而报错 >>> s = Template('Using $$ buy ${x}!') >>> s.substitute(x='food') 'Using $ buy food!' #利用字典提供键/值对 >>> 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' >>> s = Template('I am ${name},${age} years old.') >>> d = {'name':'Jerry','age':50} >>> s.substitute(d) 'I am Jerry,50 years old.' # >>> s = '%s plus %s equals %s' % (1,1,2) >>> print s 1 plus 1 equals 2------
基本的转换说明符号:
(1)%字符,标志转换的开始
(2)转换标志(可选)
------
简单转换
>>> print 'price of eggs is %d' % 12 price of eggs is 12 >>> print 'Hexadecimal price of eggs: %x' % 42 Hexadecimal price of eggs: 2a >>> from math import pi >>> 'Pi: %f...' % pi Pi: 3.141593... >>> 'very inexact estimate of pi: %i' % pi very inexact estimate of pi: 3 >>> 'Using str: %s' % 42L Using str: 42 >>> 'Using repr: %r' % 42L Using repr: 42L------
字段的宽度和精度
两个参数都是整数,用.分割,如果只给出精度,必须包含点号.
>>> '%10f' % pi #宽度为10 ' 3.141593' >>> '%10.2f' % pi #宽度为10,精度为2 ' 3.14' >>> '%.2f' % pi #精度为2 '3.14' >>> '%.5s' % 'Hello, world!' #字符串长度 'Hello' >>> '%.*s' % (5,'Hello,World!')#字符串长度,其值从元祖中读取 'Hello'------
------
------
------
------
------
------