您的位置:首页 > 编程语言 > Python开发

Python基础--使用字符串

2016-03-13 22:46 645 查看
字符串是不可变序列

[code]>>>website = 'http://www.python.org'
>>>website[-3:] = 'com'
#错误


字符串格式化–%

%左侧放置一个字符串,右侧放置希望格式化的值:

[code]>>>format = 'Hello %s %s enough for ya?'
>>>values = ('world', 'hot')
>>>print format % values
Hello world hot enough for ya?


如果字符串里包含百分号,那么就需要使用%%表示百分号。

%s中的s表示的是字符串,如果格式化浮点数,希望保留三位小数,则可以使用%.3f

元组作为%后面的参数,需要使用圆括号

[code]>>>'%s plus %s equals %s' % (1, 1, 2)
'1 plus 1 equals 2'


字段宽度和精度

[code]#字段宽度为10, 精度为2
>>>%10.2f % pi
'3.14'


find方法

查找子字符串,返回子串所在位置最左端的索引,没找到则返回-1

[code]>>>'With a moo-moo here, and a moo-moo there'.find('moo')
7
>>>'With a moo-moo here, and a moo-moo there'.find('shit')
-1


join方法

split的逆方法,要连接的必须是字符串

[code]>>>seq = ['1', '2', '3']
>>>sep = '+'
>>>seq.join(sep)
'123+'


lower方法

返回字符串小写字母版本

[code]>>>'HELLO, worldD'.lower()
hello, world


replace方法

返回某字符串的所有匹配项均被替换后得到的字符串

[code]>>>'This is a test'.replace('is', 'eez')
'Theez eez a test'


split方法

join的逆方法,将字符串分隔成序列

[code]>>>'1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']


strip方法

返回去除两侧空格的字符串,注意不包括内部

[code]>>>'       internal whitespace is kept     '.strip()
'internal whitespace is kept'


translate方法

与前面的replace有些类似,但还有不同。

首先使用maketrans完成一张转换表,然后调用translate方法

[code]>>>from string import maketrans
>>>table = maketrans('cs', 'kz')
>>>'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'


就是字符串中的c变为k, s变为z
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: