容器类型(字符串)高级使用字符串拼接和重复字符串字符串的跨行拼接字符串的索引和切片字符串的内置函数字符串的转义字符串的使用和格式化和format内置函数本文内容@[toc]字符串的拼接和重复#1.可以用+拼接多个字符串res='hello'+''+'motherland'print(res)#2.可以用*重复一个字符串res='hello'*3print(res)"""result:hellomotherlandhellohellohello"""字符串的跨行拼接接下来我们要学的是python的一个符号,拼接字符\跨行。这个符号的作用是如果一行代码太长,可以用这个符号来实现换行的功能,而原语句的功能不变。#如果变量char1的定义没有\,就是语法错误。char='hello'char1=\'hello'#字符串的跨行拼接#使用\可以实现字符串在不同行的拼接,也就是说换行的时候可以使用\代替+char='hello'+'motherland'char1='hello'\'motherland'#当然换行还是可以用+char2='hello'+\'motherland'字符串索引前面说过,字符串、列表、和元组的共同特点是有序可访问,都有正负下标索引。var='hello'print(var[1])#e字符串的切片切片顾名思义就是对字符串进行切割,并据此获取需要的元素(切片==截取)。语法:string[startindex:endindex:intervalvalue]功能:根据区间值截取从startindex所在元素到endindex之前的元素,endindex对应的元素不会被收购。[startindex:]的使用方法:截取从startindex到最后一个元素,区间值默认为1var='hellomotherland'res=var[5:]print(repr(res))#'motherland'[:endindex]:从第一个元素到endindex之前的元素截取,区间值默认为1var='hellomotherland'res=var[:5]print(repr(res))#'hello'[startindex:endindex]:截取从startindex到endindex的第一个元素,区间值默认为1var='hellomotherland'res=var[3:8]print(repr(res))#'lomo'[start:end:interval]:同第三点,但是按照指定的区间值截取var='hellomotherland'#从指定位置截取res=var[3:8:2]print(repr(res))#'lo'#默认从0开始拦截res=var[:8:2]print(repr(res))#'hlom'#逆序拦截res=var[::-1]print(repr(res))#'dnalrehtomolleh'[::],[:]:这两个是截取所有字符串#截取所有var='hellomotherland'#从指定位置截取res=var[:]print(repr(res))#'hellomotherland'#默认从0开始截取res=var[::]print(repr(res))#'hellomotherland'字符串内置函数查看字符串内置函数print(help(str))函数标题首字母大写每个单词大写首字母大写upper所有字母lower所有字母lowercaseswapcaseuppercaseandlowercaseswapcount计算一个字符的个数find找到某个字符串第一次出现的索引位置,如果没有找到返回-1index找到某个字符串第一次出现的索引位置,找不到报错startwithjudges是否以某个字符串开头,返回布尔值endswith判断是否以某个字符串结尾,返回布尔值isupper判断字符串是否大写,返回布尔值islower判断字符串是否全小写,返回布尔值istitle判断字符串中的每个单词是否大写isalnum判断字符串是否由数字、字母、汉字组成isspace判断字符串是否只由空白字符组成isdecimal判断字符串是否全部组成数字,返回布尔值ljustfillthestring,originalstringleft,returnthenewstringrjustfillthestring,originstringright,returnthenewstringcenterfillthestring,originalstringiscentered,returnthenewstringstrip去掉开头和结尾两边的空白字符,(默认为空白字符,可以指定)lstrip去掉左边的空白字符,(默认为空白字符,可以指定)rstrip去掉右边的空白字符,(默认为空白字符,可以指定)split根据指定字符将字符串拆分成列表rsplit将字符串按照指定的字符从右到左拆分成列表join将容器按照一定的字符串转换成字符串replace将字符串中的字符替换为其他格式字符串的格式化capitalizevar='hellomotherland'res=var.capitalize()print(res)#Hellomotherlandtitlevar='hellomotherland'res=var.title()print(res)#HelloMotherlanduppervar='hellomotherland'res=var.upper()print(res)#HELLOMOTHERLANDlowervar='HELLOMOTHERLAND'res=var.lower()print(res)#hellomotherlandswapcasevar='HelloMotherland'res=var.swapcase()print(res)#hELLOmOTHERLANDcount语法:string.count(sub,[start,],[end])string.count(string,[startvalueindex],[endvalueindex])#注意count区分大小写var='HelloMotherland'res=var.count('h')print(res)#1res=var.count('H',3,10)print(res)#1findandindex语法:string.find(sub,[start,],[end])语法:string.index(sub,[start,],[end])#查找并索引服务案例var='HelloMotherland'res=var.find('h')print(res)#9res=var.index('h')print(res)#9#如果字符不能find,find返回-1,index报错res=var.find('m',3)print(res)#-1res=var.index('m',3)print(res)#error#findonly将返回正向索引,所以不用担心如果您要查找的字符是最后一个字符怎么办var='HelloMotherland'res=var.find('d')print(res)#15print(len(var))#16startswithandendswithSyntax:startswith(prefix,[start],[end])Syntax:endswith(suffix,[start],[end])var='HelloMotherland'#检查整个字符串是否以Hello开头res=var.startswith('Hello')print(res)#True#检查索引6处的字符串是否以Mother开头res=var.startswith('Mother',6)print(res)#True#检查整个字符串是否是以aadres=var.endswith('aad')pri结尾nt(res)#Falseisupperandislowervar='HelloMotherland'#判断字符串是否全大写res=var.isupper()print(res)#False#判断字符串是否全小写res=var.islower()print(res)#错误eisdecimalvar='20666'#判断字符串是否由数字组成res=var.isdecimal()print(res)#Trueljust,rjust,center语法:string.ljust(width,[fillchar])指定一个长度,如果字符串如果长度不够,就按照指定的字符串补上。默认使用空格,用于填充的长度长度不能超过1var='你好祖国'res=var.ljust(20)print(repr(res))#'HelloMotherland'res=var.rjust(30,'m')print(res)#mmmmmmmmmmmmmmHelloMotherlandprint(len(res))#30res=var.center(30,'-')print(res)#------你好祖国--------strip,lstrip,rstripvar='你好祖国'#去掉第一边和最后边Stringres=var.strip()print(repr(res))#'HelloMotherland'var='mmmmmmmmHelloMotherlandmmmmmm'#去掉左边的res=var.lstrip('m')print(repr(res))#'HelloMotherlandmmmmmm'#去掉左边的resright=var.rstrip('m')print(repr(res))#'mmmmmmmmHelloMotherlandmmmmmm'#最右边不是m开头的,所以split和rsplit不能去掉var='Hellomymotherland'#Default分隔空格,全部分开res=var.split()print(res)#['Hello','my','motherland']#指定分隔个数res=var.split('',1)print(res)#['你好','我的祖国']#指定分隔符res=var.split('l')print(res)#['他','','o我的妈妈','and']#rsplit从中拆分res从右到左=var.rsplit('l')print(res)#['He','','omymother','and']#嗯?rsplit的结果和rsplit的结果怎么一样?rsplitd的意思并不是说list的元素的排列结果是从右往左的,而是从字符串的右边开始找一个字符。如果我们只将它分开一次,我们可以看到结果的不同。#rsplit从右到左分开res=var.rsplit('l',1)print(res)#['Hellomymother','and']#splitres从左到右=var.split('l',1)print(res)#['He','lomymotherland']#看出区别了吗?joinlst=['h','e','l','l','o']res='-'.join(lst)print(res)#h-e-l-l-ostring='hello'res='-'.join(string)print(res)#h-e-l-l-oreplace语法:string.replace(old,new,[count])var='hellohellomymotherland'#替换里面的字符res=var.replace('hello','Hello')print(res)#hellohellomymotherland#替换其中一个字符res=var.replace('hello','hi',1)print(res)#hihellomymotherlandstring的使用ofescape转义字符python中的转义字符指的是\,它的作用是让这个符号后面的字符变得无意义,无意义变得有意义。无意义字符是指简单的字符串字符;有意义的字符是指不是表面上看到的字符,而是具有另一层特殊含义的字符。转义字符符号的主要作用是\n换行符(Unix或Linux)\r\n换行符(windows)\tindentation\r用这一行前面的所有字符替换这一行之后的所有字符\bbackspace,删除一个字符var='hello\nmotherland'print(var)print()var='hello\r\nmotherland'print(var)print()var='hello\tmotherland'print(var)print()var='hello\r\nmotherland'print(var)#退格符用来删除一个字符strvar='abcde\bfg'print(strvar)#abcdfg有一些特殊的路径地址带有一些转义字符,但是我们不希望这些定义字符可以执行,可以使用原型输出。#路径被转义了,如何解决?var='C:\Windows\twain_32'print(var)#C:\Windowswain_32#方法一:使用\让转义字符无意义var='C:\Windows\\twain_32'print(var)#C:\Windows\twain_32#方法二:使用repr函数原型输出var='C:\Windows\twain_32'res=repr(var)print(res)#'C:\\Windows\twain_32'#方法三:使用元字符'''在字符前加r表示该字符串的原型输出,不再执行字符串中的任何转义字符。'''var=r'C:\Windows\twain_32'print(var)#C:\Windows\twain_32格式字符串使用占位符来替换字符串中的一个字符,这样这个位置的字符就可以任意替换了。Placeholder%d整数占位符%f浮点数占位符%s字符串占位符整数占位符可以用整数、小数、布尔值填充#可以用整数填充var='Ihave%dblocksMoney'%(100)print(var)#我有100块钱#也可以填小数,但是显示的效果是整数var='我有%d块钱'%(100.99)print(var)#我有100块钱#填入布尔值和转换成对应的整型var='Ihave%ddollars'%(True)print(var)#Ihave1dollar浮点占位符和整型一样,可以填Integer,decimal,Boolean#小数可以填var='我的车的排量是%fT'%(2.0)print(var)#我的车的排量是2.000000T#也可以填整数,但是显示的效果是Decimalvar='Mycar'sdisplacementis%fT'%(2)print(var)#Mycar'sdisplacementis2.000000T#可见小数点保留的太多了。字符串占位符可以随便填python的合法类型#可以填小数var='mycar'sdisplacementis%sT'%(2.0)print(var)#mycar'sdisplacementis2.0T#也可以填整数,但是显示的效果是小数var='Thedisplacementofmycaris%sT'%(2)print(var)#我的车的排量是2T#也可以填整数,但是显示的效果是小数var='我的车的排量是%sT'%(True)print(var)#我的车的排量是TrueT#多个占位符的使用var='我的车是%s,花了%d万,占%f%%ofmytotalasset'%('BYD',50,0.000001)print(var)#我的车是比亚迪,50万,占我总资产的0.000001%#注意,在格式化字符串的时候,如果你想单独打印一个%,需要输入两个%%,消除%的占位意义。format函数的使用也是对字符串进行格式化,但是比上面的方法更强大。format使用大括号代替占位符,并将值作为自己的参数传递。Syntax:'string{}{}'.format(value1,value2)顺序传参,按照占位符和值的顺序一对一传递#任何数据类型都可以传,默认是字符串占位符。var='{}{}'.format('hello','motherland')print(var)#hellomotherland索引传参在方括号中填写格式参数的索引值,传参#反下标不支持Indexvar='{1}{0}'.format('hello','motherland')print(var)#motherlandhello关键字作为关键字传给参数,然后填入名字方括号中的关键字,关键字根据对应的名字传值。var='{msr}{world}'.format(msr='hello',world='motherland')print(var)#hellomotherland容器类型参数如果参数是容器类型的数据,可以在括号中填写容器对应的索引值来传递参数。lst=['hello','goodbye']tup=('my','your')dit={'one':'motherland','two':'world'}#不指定容器中的元素var='{}{}{}'.format(lst,tup,dit)print(var)#['你好','再见']('我的','你的'){'一个':'祖国','two':'world'}#指定元素#字典的key不需要加引号var='{[0]}{[0]}{[one]}'.format(lst,tup,dit)print(var)#你好我的祖国可以使用填充符号来填充不够长的字符串^原字符串居中\>原字符串右<原字符串左语法:{[关键字参数]:[待补字符][原字符串位置]\<总字符长度>}例子:{who:*^10}who:关键字参数,或下标索引*:待补字符(空格为默认填充)^:原始字符串位置(默认左边)10:总字符长度=原始字符串长度+填充字符长度var='{price:-^20}'.format(price='price')print(var)#---------price--------#注意,中间:不可或缺var='{:*^10}'.format('price')print(var)#****Price****使用十进制转换符号:d整数占位符:f浮点数占位符:s字符串占位符:,Money占位符#整数占位符#要求数据类型必须是一个整数,不兼容除整数以外的任何数据类型var='MyCar{:d}10,000'.format(100)print(var)#MyCar1,000,000#如果有数字要求,添加数字;如果有地方可以使用填充符号strvar='Ihave{:^10d}dollars'.format(100)print(strvar)#Ihave100dollars#浮点占位符,要求的数据类型必须是floatvar='我用{:f}%的资产泡妞。'.format(100.00)print(var)#我用100.000000%的资产泡妞。#需要保留两位小数,use.numvar='我用{:.2f}%的资产泡妞。'.format(100.00)print(var)#我用100.00%的资产泡妞。#字符串占位符,要求的数据类型必须是字符串var='我的房子在{:s}{:s}'.format('北京','十八环')print(var)#我的房子在北京十八环#moneyplaceholder#按千位隔开一串数字var='我有存款{:,}元'.format(100000000)print(var)#我有存款100,000,000元
