字符串查询统计
t = 'lblal al'
#count()统计a的个数
print(t.count('a'))
print(t.count('b'))
#查找时,从左至右查找,找到第一个时返回其下标
print(t.find('a'))
#统计字符串长度
print(t.__len__())
#index和find一样,从左至右查找
print(t.index('a'))
format和format_map区别
#format方法传参需要传入(参数 = 真实值),或者传入映射的字典
student = {"name":"xiaoming","age":15,"score":540}
print("{st[name]}的年龄为{st[age]},总分为{st[score]}".format(st = student))
#format_map传入的可以是一个真实的字典
print("{name}的年龄为{age},总分为{score}".format_map(student))
字符串空格处理
#strip()去除空格,会去出前后的空格,但是不会去除中间的空格
t1 = ' abdcd dda '
print('===strip===')
print(t1)
print(t1.strip()) #去除前后空格
print(t1.rstrip()) #去除右边的空格
print(t1.lstrip()) #去除左边的空格
#isspace是否是空格
s = ' '
s1 = '1 '
print(s.isspace())
print(s1.isspace())
print('=====isalpha====')
字符串类型判断
#isalpha()如果是纯字符返回True,否则返回False
#isdigit()如果字符串是纯数字返回True,否则返回False
s2 = '1122'
s3 = 'a123'
s4 = 'abcdd'
print(s2.isalpha())
print(s3.isalpha())
print(s4.isalpha())
print("=====isdigit====")
print(s2.isdigit())
print(s3.isdigit())
print(s4.isdigit())
字符串大小写转换
#upper把字符串全部转换为大写
#lower把字符串全部转换为小写
s5 = 'HAHAhahaha'
print(s5.upper())
print(s5.lower())
字符串转list
#split()把字符串已输入的字符做分隔符转换为list,注:切分str为list
#replace() 把str中的字符替换,注:修改字符串
s6 = 'xiaowang,xiaobai,xiaohei,xiaohong'
print(s6[:8],'\n',s6[9:16],'\n',s6[17:24],'\n',s6[25:33])
s7 = s6.split(",")
print(s7)
print(s6.split(" "))
print(s6.replace(',','\n')) #把字符串用\n(换行符)替代','的方式输出
print('=======倒序=======')
s7.reverse() #由于s7.reverse()没有输出,所以必须单独写一行执行list反转
for i in s7:
print(i)
# s8 = s7[::-1] #另一种原始方式实现list反转
# for i in s8:
# print(i)
log = '223.104.3.169 - - [03/Jul/2020:17:09:31 +0800] "GET /bbs/forum.php HTTP/1.1" 404 1045 "-" "Apache-HttpClient/4.5.10 (Java/1.8.0_201)"'
log_list = log.split(' ')
print(log_list[0])
判断字符串开始和结束字符
s9 = 'hahahd'
print(s9)
print(s9.startswith('h'))
print(s9.startswith('1'))
print(s9.endswith('a'))
print(s9.endswith('d'))