码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础--使用字符串

时间:2016-03-14 18:59:05      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

字符串是不可变序列

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

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

>>>format = ‘Hello %s %s enough for ya?‘
>>>values = (‘world‘, ‘hot‘)
>>>print format % values
Hello world hot enough for ya?

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

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

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

>>>‘%s plus %s equals %s‘ % (1, 1, 2)
‘1 plus 1 equals 2‘

字段宽度和精度

#字段宽度为10, 精度为2
>>>%10.2f % pi
‘3.14‘

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

>>>‘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的逆方法,要连接的必须是字符串

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

lower方法
返回字符串小写字母版本

>>>‘HELLO, worldD‘.lower()
hello, world

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

>>>‘This is a test‘.replace(‘is‘, ‘eez‘)
‘Theez eez a test‘

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

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

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

>>>‘       internal whitespace is kept     ‘.strip()
‘internal whitespace is kept‘

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

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

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

就是字符串中的c变为k, s变为z

Python基础--使用字符串

标签:

原文地址:http://blog.csdn.net/wangshubo1989/article/details/50880239

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