python字符串用法

目录

 (红色部分是重点)
1,%或format 格式化
2,strip 去除收尾字符
3,[:5] 切片 [0:5]顾头不顾尾 [:-5]下标为-5(包括-5)
4,count 统计
5,swapcase 小写变大写 upper大写
6,join 将列表变成表格
7,replace 替换
8,index 查看下标
9,split 切分 rsplit 从右往左切 lsplit 从左……
10,判断 istitle是否是抬头 startswith('w')是否以w结尾 ……
11,encode 转码
12,+ 拼接
13,find 查找
 
trip 去除
lower 小写
isspace 是否是空格字符串,而不是判断字符串里是否有空格
 
 
具体用法
 
res = 'hello,world' #以下带******的为重点
 
1,字符串格式化(%s和format)******
# result = 'my name is {name}, my age is {age}'.format(name='申晨林', age=25)
# result1 = 'my name is {0}, my age is {1}'.format('申晨林',25)
# result = 'my name is %s, my age is %s' % ('申晨林', 25)
# result1 = 'my name is %s' % '申晨林'
 
2,strip去除首尾字符*******
#res1 = '=====hello,world====='
# print(res1.strip('='))
 
去除右边的字符
# print(res1.rstrip('='))
 
去除左边的字符
# print(res1.lstrip('='))
 
从右往左切,以.为分割,切3刀*******
# res1 = '192.168.1.1'
# print(res1.rsplit('.', 4))
 
3,字符串切片:[0:5]顾头不顾尾,[0:11:2]步长为2也就是隔一个取一个,[:-5]下标为-5(包括-5)往右的字符不要了,[5:]下标为5(不包括5)往左的字符不要了, [4]去字符串中下标为4的字符*******
# print(res[0:5])
# print(res[0:-1:2])
# print(res[:-5])
# print(res[5:])
# print(res[5:][4])
 
4,统计字符串里字符的个数*******
# print(res.count('l'))
 
5,小写字母变大写
# print(res.swapcase())
# print(res.upper())
 
6,把列表变成字符串*******
# s = ''.join(['a','b','c'])
 
7,字符串替换*******
# print(res.replace('l', 'sb', 2))
 
8,查找字符串中最靠左元素的下标*******
# print(res.index('o'))
 
9,把字符串变成列表(以l分割点)*******
# print(res.split('l'))
 
10,判断是否是抬头
# print(res.istitle())
判断字符串开头字符是否是(w)
# print(res.startswith('w'))
判断是否是小写
# print(res.islower())
判断字符串结尾的字母
# print(res.endswith('w'))
 
11,#encode转码,decode解码*******
# res1 = '你好'
# a = res1.encode('utf-8')
# print(a.decode('utf-8'))
 
12,#字符串拼接*******
# res1 = 'my name is'
# res2 = '申晨林'
# print(res1+res2)
 
13,find是查找字符串里的元素下标,如果没有返回-1
# print(res.find('qq'))
原文地址:https://www.cnblogs.com/lichenghong/p/10534872.html