字符串运算
#1.字符串连接,使用+ str1='hello' str2='world' print(str1+' '+str2) #重复输出字符串,用* #2.重复输出字符串 str1='hello' print(str1*3) #3.截取字符 str1='hello' print(str1[2:]) print(str1[:2]) print(str1[:-1]) #4.通过索引获取字符串中的字符 str1='hello' print(str1[2]) #5.判断字符串中是否包含指定字符,存在返回True,不存在返回False str1='hello' print("a" in str1) #6.判断字符串中是否不包含指定字符,存在返回True,不存在返回False str1='hello' print('a' not in str1) #7.原始字符串,主要讲一些用于转义的符号以本来的面目显示 print(r'\n')转义字符(写几个常用的)
\(用于行尾) 两行当一行使用(比如规范书写一行不超过79个字符,超过的可以使用这个另起一行) \\(反斜杠) 文件读写操作指定路径时会用到 \n(换行) 由于换行,由于默认打印语句会添加,所以反而不需要的时候用end=''去除换行符多行字符串
#多行字符串 strs=''' 这里就不需要顾忌语法格式,是什么, 打印出来的就是什么,不会被束缚 ''' print(strs)字符串内置方法
#1.把字符串的第一个字符大小 str='hello world' print(str.capitalize()) #2.设定字符长度占位,将指定字符放至其中间,两端用空格填充 str='hello world' print(str.center(30)) #3.统计字符在字符串中出现的个数 str1='hello world' print(str1.count('l',0,len(str1))) #这里的0,len(str1)是指的搜索的下标范围 #4.将字符串中的小写字母转为大写 str1='hello world' print(str1.upper()) #5.删除字符串开头和末尾的空格 str1=' hello world ' print(str1) #6.以某符号为分隔符切片字符串,以列表的形式存储被分隔的字符子串 str1='hello world f' print(str1.split(' '))转载于:https://www.cnblogs.com/endmoon/p/9683139.html