数据类型-字符串字符串是python中最常见的基本数据类型之一。常见的定义是一对单引号('...')或一对双引号("..."),也可以使用三重单引号或三重双引号定义多行字符串。1.特点不可变类型:元素定义后不能修改,否则会报错可以进行切片和索引操作:索引下标从零开始例子a="helloworld"b='hellopython'print(type(a),type(b))print(type(a),type(b))打印输出显示,可以看出一个变量的类型和b变量都是str字符串,type内置函数用于查看变量或对象的类型。2、索引和切片下标也叫索引,用来记录元素的位置,以便通过下标快速找到对应的数据。字符串的下标从0开始,在使用过程中要注意索引越界语法的问题。序列[索引位置]示例print(a[0])print(a[1])如果索引值超过字符串长度,程序会抛出错误IndexError:stringindexoutofrangeSlicing是指截取一部分被操作对象的,切片索引超过元素最大索引不会报错,按照最大索引返回语法序列[起始位置下标:结束位置下标:步长]name="abcdefg"print(name[2:5:1])#cdeprint(name[2:5])#cdeprint(name[:5])#abcdeprint(name[1:])#bcdefgprint(name[:])#abcdefgprint(name[::2])#acegprint(name[:-1])#abcdef,负1表示第一个最后一个数据print(name[-4:-1])#defprint(name[::-1])#gfedcbaslice满足header不满足tail根据规则,正负数相同。步长是可选参数。如果不传,默认为1自增。模)运算符。这也称为字符串的格式化或插值运算符。转换器描述d有符号十进制整数i有符号十进制整数o有符号八进制f浮点十进制格式r字符串(使用repr()转换任何Python对象)s字符串(使用str()转换任何Python对象)a字符串(使用ascii()转换任何Python对象)%不转换参数,在结果中输出一个'%'字符age=18name='TOM'weight=75.5stu_id=1stu_id2=1000#1.我今年的年龄是x岁--Integer%dprint('我今年的年龄是%d岁'%age)#结果:我今年的年龄是18岁#2.我的名字是x--String%sprint('我的名字是%s'%name)#Result:MynameisTOM#3.Myweightisxkg--float%fprint('Myweightis%.3fkg'%weight)#Result:Myweightis75.500kg#4.我的学生证是x--%dprint('我的学号是%d'%stu_id)#结果:我的学号是1#4.1我的学号是001print('我的学号是%03d'%stu_id)print('我的学号是%03d'%stu_id2)#结果:我的学号是001#结果:我的学号is1000#5.我叫x,今年x岁print('我叫%s,今年我%d岁'%(name,age))#结果:我叫TOM,我是今年18岁#5.1我叫x,明年我是x岁print('我叫%s,明年我是%d岁'%(name,age+1))#result:我叫TOM,明年我19岁#6.我叫x,今年x岁,体重x公斤,学号是xprint('我叫%s,我今年%d岁thisyear,weight%.2fkg,studentIDis%06d'%(name,age,weight,stu_id))#结果:我叫TOM,今年18岁,体重75.50公斤,学号is0000013.2Stringformat()methodage=18name='TOM'weight=75.5stu_id=1stu_id2=1000print('我叫{},今年{}岁,体重{}公斤,学号为{}'。格式(name,age,weight,stu_id))print('我叫{name},今年{age}岁,体重{weight}公斤,学号是{stu_id}'.format(stu_id=stu_id,weight=weight,name=name,age=age))花括号和其中的字符(称为格式字段)将被传递给str.format()方法的对象替换。大括号中的数字可用于表示方法对象的位置。3.3f{}formatstringage=18name='TOM'weight=75.5stu_id=1stu_id2=1000print(f'我叫{name},我今年{age}岁,我的体重是{weight}公斤,并且我的学号是{stu_id}'))fformatstring方法可以说是str.format()方法的简写形式4String常用方法4.1Search对于字符串,应该经常用到查找的位置一个元素。Search就是找出该元素在字符串中出现的位置或者出现的次数find():检查字符串中是否包含某个子串。如果子串开头有下标,不存在则返回-1。语法字符串sequence.find(substring,开始位置下标,结束位置下标)例子mystr="helloworldanditcastanditheimaandPython"print(mystr.find('and'))#12print(mystr.find('and',15,30))#23print(mystr.find('ands'))#-1起始位置下标和结束位置下标可以省略。如果不传参数,默认在整个字符串中findindex():检查这个字符串中是否包含某个子串,如果存在,则返回该子串开头的下标,如果不存在,返回一个会报异常。语法字符串sequence.index(substring,开始位置下标,结束位置下标)示例mystr="helloworldanditcastanditheimaandPython"print(mystr.index('and'))#12print(mystr.index('and',15,30))#23print(mystr.index('ands'))#ErrorValueError:rfind():与find()功能相同,但搜索方向从右开始。rindex():与index()功能相同,但查找方向从右侧开始。count():返回子字符串在字符串中出现的次数'and'))#3print(mystr.count('ands'))#0print(mystr.count('and',0,20))#14.2修改后的字符串是不可变类型,修改指的是以函数replace()的形式修改字符串中的数据:replacesyntaxstringsequence.replace(oldsubstring,newsubstring,replacementtimes)examplemystr="helloworldanditcastanditheimaandPython"print(mystr.replace('and','he'))#Result:helloworldheitcastheitheimahePythonprint(mystr.replace('and','he',10))#结果:helloworldheitcastheitheimahePythonprint(mystr)#结果:helloworldanditcastanditheimaandPython替换的个数可以省略。默认是所有字符串都被匹配并且会被改变。如果传入替换次数,找到子串出现的次数,替换的次数就是这个根据子串出现数据是否可以直接修改,分为变量型和不可变型两种.修改字符串类型的数据时,不能改变原来的字符串,不能直接修改数据的类型是不可变类型。split():根据指定的字符拆分字符串。语法stringsequence.split(separationcharacter,num)num表示分割字符出现的次数,即以后返回的数据个数为num+1。示例mystr="helloworldanditcastanditheimaandPython"print(mystr.split('and'))#result:['helloworld','itcast','itheima','Python']print(mystr.split('and',2))#result:['helloworld','itcast','itheimaandPython']print(mystr.split(''))#result:['hello','world','and','itcast','and','itheima','and','Python']print(mystr.split('',2))#结果:['hello','world','anditcastanditheimaandPython']如果拆分后的字符是原字符串字符串中的子串,则拆分后该子串丢失。join():合并具有一个字符或子串的字符串,即将多个字符串组合成一个新的字符串。语法字符或子串。join(多个字符串的序列)示例list1=['I','love','you']t1=('aa','b','cc','dd')print('_'.join(list1))#Result:I_love_youprint('...'.join(t1))#Result:aa...b...cc...dddcapitalize():convertthestring将字符转换为大写。例子mystr="helloworldanditcastanditheimaandPython"print(mystr.capitalize())#结果:Helloworldanditcastanditheimaandpythoncapitalize()函数转换后,只有字符串首字符大写,其他字符全部小写。title():将字符串中每个单词的首字母转为大写。示例mystr="helloworldanditcastanditheimaandPython"print(mystr.title())#结果:HelloWorldAndItcastAndItheimaAndPythonlower():将字符串中的大写字母转换为小写字母。示例mystr="helloworldanditcastanditheimaandPython"print(mystr.lower())#结果:helloworldanditcastanditheimaandpythonupper():将字符串中的小写字母转换为大写字母。示例mystr="helloworldanditcastanditheimaandPython"print(mystr.upper())#结果:HELLOWORLDANDITCASTANDITHEIMAANDPYTHONlstrip():删除字符串左侧的空白字符。rstrip():删除字符串右侧的空白字符。strip():去除字符串两边的空白字符。ljust():返回一个与原字符串左对齐并用指定字符(默认空格)填充到相应长度的新字符串。语法字符串sequence.ljust(length,fillcharacter)示例mystr='hello'mystr1=mystr.ljust(10,'.')print(mystr1)#result:hello.....rjust():returnaprimitiveRight-对齐字符串,用指定的字符(默认空格)填充相应长度的新字符串。语法与ljust()相同。center():返回一个与原字符串居中对齐并用指定字符(默认空格)填充到相应长度的新字符串。语法与ljust()相同。例子mystr='hello'mystr1=mystr.center(10,'.')print(mystr1)#结果:..hello...4.3判断判断是指是否满足条件,返回结果为布尔型type,TrueorFalsestartswith():检查字符串是否以指定的子字符串开头,如果是则返回True,否则返回False。如果设置开始和结束位置下标检查指定范围内。语法字符串sequence.startswith(substring,开始位置下标,结束位置下标)例子mystr="helloworldanditcastanditheimaandPython"print(mystr.startswith('hello'))#result:Trueprint(mystr.startswith('hello',5,20))#ResultFalseendswith()::检测字符串是否以指定子串结尾,是则返回True,否则返回False。如果设置开始和结束位置下标检查指定范围内。语法字符串sequence.endswith(substring,开始位置下标,结束位置下标)示例mystr="helloworldanditcastanditheimaandPython"print(mystr.endswith('Python'))#Result:Trueprint(mystr.endswith('python'))#Result:Falseprint(mystr.endswith('Python',2,20))#Result:Falseisalpha():如果字符串至少有一个字符且所有字符都是字母则返回True,否则返回False。示例mystr1='hello'mystr2='hello12345'print(mystr1.isalpha())#结果:Trueprint(mystr2.isalpha())#结果:Falseisdigit():如果字符串仅包含数字,则返回True,否则返回False。示例mystr1='aaa12345'mystr2='12345'print(mystr1.isdigit())#Result:Falseprint(mystr2.isdigit())#Result:Falseisalnum():如果字符串至少有一个字符并且所有字符都是字母或者数字返回True,否则返回False。示例mystr1='aaa12345'mystr2='12345-'print(mystr1.isalnum())#Result:Trueprint(mystr2.isalnum())#Result:Falseisspace():如果字符串只包含空格,则返回True,否则返回False.mystr1='12345'mystr2=''print(mystr1.isspace())#result:Falseprint(mystr2.isspace())#result:True