Python数据类型(二):字符串类型一

来源:互联网 发布:库里2015赛季数据 编辑:程序博客网 时间:2024/06/07 11:59

字符string类型是python的内置的数据类型,也提供了非常多操作字符串的功能,几乎你能想到的跟字符相关的功能都有。

针对字符串的常用操作是增、删、查、改


1、字符串的表示


1.1、引号的用法

跟其他编程语言不一样,python中可以同时使用单引号和双引号,并且意思一样的,只不过要一一配对使用,下面的字符串是等价的

str1 = " I am arwen,what's your name? "  #外面两个双引号,中间有一个单引号str2 = ' I am arwen,what\'s your name? '  #外面两个单引号,中间的单引号需要加斜杠\转义print str1,str2#结果 I am arwen,what's your name?   I am arwen,what's your name? 

1.2、多行显示

下面的两个字符串是等价的

str1 = ' Life is short, \n'\       ' I use python'    #两行独立的字符串通过烦斜杠\连接起来多行显示str2 = '''Life is short ,I use python'''    #3个单引号str3 = """Life is short ,I use python"""  #3个双引号

1.3、字符串的前缀R、U

content_info = 'Life is short \n' print  content_info   #\n是换行转义字符,肯定不会显示出来,那假如我们的内容中就是需要这个展示这个转义字符呢content_info  = R'Life is short \n'   #用R做前缀后,字符串里的\n就当做普通内容处理了,R换成小写的r是一样的。#使用R较多的地方是目录路径、正则表达式、内容中有转义字符print content_infoinfo = U'unicode string'   #使用U或u表示unicode字符串#结果Life is short Life is short \n

2、字符串的增加操作

增加嘛主要是插入、连接

2.1、字符串连接

2.1.1 、使用+连接

通过+把字符连接起来是很多编程语言中的用法

first = 'Beautiful is better than ugly;'second = 'Simple is better than complex;'ret = first + second


2.1.2、使用占位符

字符串占位符

input_one = 'arwen'input_two = 'candy'info = '%s love %s'%(input_one, input_two)print info # 结果是arwen love candy

假如想把排版弄漂亮点,可以在字符串前面和后面加些空格。

str_one = '%10s'%'py'  #在py前面加10个空格str_two = '%-10s'%'py' #在py后面加10个空格print str_one , str_two, 'end'#结果        py py         end

整数占位符

info = '%d, %o, %x'%(10,010,0x10)  #%d、%o、%x分别表示10进制、8进制、16进制的整数print info  #结果为10, 10, 10


浮点数占位符

info = '%f, %.2f'%(3.12545678, 3.12545678)
print info  #结果为3.125457, 3.13

>>> info = '%f, %.2f'%(3.12545678, 3.12545678)>>> print info3.125457, 3.13# %f默认是显示6位小数,如果超出6位会四舍五入做截断,如果指定了长度就会按指定的长度四舍五入截断(在f前加点.和数值指定小数位数)


另外还有个%e,是通过小数加指数的形式来展示

>>> info = '%e'%0.00000003>>> print info3.000000e-08#也是默认显示6位小数,可以跟%f一样通过.2这样来指定小数位数


2.1.3、使用format

format的功能跟占位符类似,不过功能更强大。通过{}和:来替代%

zen = 'Beautiful is {0} than {1};Simple is {0} than {2} ;\n'.format('better','ugly','complex')ret = 'the result of 1.0/3 is {zero:.2f},1/3 is {one}'.format(one=1/3,zero=1.0/3)print zen, ret#结果Beautiful is better than ugly;Simple is better than complex ;the result of 1.0/3 is 0.33,1/3 is 0
除了通过{0}、{1}这样按位置指定,还可以通过{zero}、{one}这样关键字来指定。关键字指定传参的顺序就不受限制;

另外可以通过:.2f这样加很多属性来限制显示。

>>> print 'Display number {0:d},{1},{2} {1:o},{2:x}'.format(10, 010, 0x10)Display number 10,8,16 10,10


2.1.4、使用join

join可以把数组、列表等转化为字符串,并且可以在每个元素间添加些内容

array = ['Now','is','better','than','never']tup = ('Now','is','better','than','never')dic = {'Now':0,'is':1,'better':2,'than':3,'never':4}print ''.join(array),'\n'print ' '.join(array),'\n'print '-'.join(tup),'\n'print ':'.join(dic)#结果Nowisbetterthannever Now is better than never Now-is-better-than-never better:is:Now:than:never


3、字符串删除、替换操作


3.1、strip

str.strip() #strip不指定参数的时候默认删除字符串开头和结尾处的空白字符'\n', '\t', '\r';

如果指定了参数就是在开头和结尾删除指定的字母;

另外lstrip、rstrip只删除开头和结尾,或者是说字符的最左边和右边,lstrip、rstrip就是leftstrip、rightstrip简称

</pre><pre name="code" class="python">>>> print '\n Zen of python' Zen of python>>> print '\n zen of python'.strip()zen of python>>> print '\t Beautiful is better than ugly' Beautiful is better than ugly>>> print '\t Beautiful is better than ugly'.strip()Beautiful is better than ugly>>> print '#Zen of python#'#Zen of python#>>> print '#Zen of python#'.strip('#')Zen of python>>> print 'zen of python'.strip('zen') of pytho #这里zen是删除开头和结尾的字母z、e、n>>> print '#zen of python#'.lstrip('#')zen of python#>>> print '#zen of python#'.rstrip('#')#zen of python>>> 


3.1.1、空白字符\n、\r、\t

刚提到了空白字符,不过其实很多时候很多人比较容易迷糊\n、\r的区别,\t比较好理解,制表符,一般默认是4个空格。

而\n、\r在不同平台意思不一样

这不是python的问题,windows的换行是\r\n,unix的是\n,mac的是\r。这样假如拿来一个文本文件,在不同平台处理换行就有问题了。有个比较简单的处理方法。

如果不是txt文件,建议用wb和rb来读写。通过二进制读写,不会有换行问题。
如果需要明文内容,请用rU来读取,即U通用换行模式(Universal new line mode)。该模式会把所有的换行符(\r \n \r\n)替换为\n。只支持读入

info = file(fn, 'r').read()


3.2、replace

replace顾名思义就是替换字符串里面部分内容,第一个参数是字符串里的某个字符,第二个参数是要替换的字符,第三个参数是限制替换的次数

>>> print 'C++ is complex, python is simple'.replace('is','is not')C++ is not complex, python is not simple>>> print 'C++ is complex, python is simple'.replace('is','is not',1)C++ is not complex, python is simple>>> 


4、字符串查找


info = 'python is simple'print info.find('i')print info.find('is')print info.find('c++')print info.index('i')print info.index('is')print info.index('c++')#结果77-177 rint info.index('c++')ValueError: substring not found

find查找到了字符或字符串就返回对应的索引下标、如果没找到就返回-1

index查找到了字符或字符串就返回对应的索引下标、如果没找到就抛出异常

另外还有两个类型的方法rfind、rindex,功能一样,只不过是从字符串结尾开始查询


5、字符串变换


5.1、字符串大小写转换

>>> info = 'python is simple'>>> print info.upper()PYTHON IS SIMPLE>>> print info.lower()python is simple


5.2、字符串分割

info = 'life is short'lst = info.split(' ')print lst#结果['life', 'is', 'short']
split是把字符分割成数组


5.3、字符串截取

info = 'life is short'print info[1:5]print info[0:]print info[:5]print info[0:-1]#结果ife life is shortlife life is shor

截取字符串就是把字符串当做数组一样,通过开始和结束的的索引下标指定,结束的索引对应的字符不在截取之列;

另外开始或结束索引为空不填的话就意味着最左边、最后边的字符下标,并且在截取之列;

索引为负数表示从右边开始计算;


0 0