数据结构字符串

162 阅读1分钟

1、字符串前加r

2、序列 `https://blog.51cto.com/huangyg/2316479
3、len()函数

msg='helloworld'
print(len(msg))
输出结果:10

4、in与not in 运算符 print ('ap in msg', 'ap' in msg ) 5、find方法

price='mate20:4999 xiaomi8:4199 OPPOR17:4299')
print (price.find('x'))
输出结果:12
print (price.find('vivo'))
输出结果:-1  #不存在返回-1

rfind()从后面开始查找 与find相同 index()与find方法相同,不同:不存在不报异常 6、S.count统计字符串 print (price.count('vivo'))

7、切分

S.plit() 空字符切分默认包括:空格、回车等

8、拼接 join方法

9、切片

[:]整体输出 [1:]去除第一字符 [:-1]去除最后字符 10、练习:nums=[1,2,3] 转化为123

nums=[1,2,3]
tmp=str(nums)[1:-1]   #如何去掉[],使用切片操作
print(tmp)
tmp=tmp[1:-1]          #切片操作
print(tmp)

输出结果:1, 2, 3
         , 2, 

11、替换 S.replace(old,new[,count])

s ='80,none,90,none'
print (s.replace('none','0',1))
输出结果:80,0,90,none

12、strip移除字符串

如:S.strip('#-') 13、字符串开头结尾判断 S.startswith() S.endswith() 14、大小写转化

15、format函数 占位符

f='{1} age {1}'
print(f.format('aa',2,3))
输出结果:2 age 2