Python字符窜取值


'''
https://www.cnblogs.com/xiazhenyu/
*** 学而思之、思而记之、记而习之 ***
'''

#
coding:utf-8 msg = "hello world *te*st *?/ * / -*2ego2*n , -*= 123" #按索引取值 print(msg[0],type(msg))#取第一个值 print(msg[-1],type(msg))#取最后一个值 #按切片取值 print(msg[1:4],type(msg))#取固定范围值,顾头不顾尾;左闭右开;从前面取值; 从左往右,正向 print(msg[-3:-1],type(msg))#取固定范围值,顾头不顾尾;左闭右开;从后面取值; 从左往右,正向 print(msg[-1:-3:-1],type(msg))# 从右往左,反向取值必须指定步长(反向取值步长也是负数) print(msg[6:13:2],type(msg))# wld*,在固定范围中 每有两个取其中前一个,指定步长为2 print(msg[6:],type(msg))# 取固定范围值,指定开头到结尾,结尾不用写,反之一样 print(len(msg))# 取字符串长度 #成员运算,判断一个子字符串是否在另一个字符窜中,使用in或not in response_msg = "this is a boy" print('boy' in response_msg)#返回True,判断成功 # 移除空白 strip msg = " * **/,hello wor*ld**=** " print(msg.strip())#strip不指定数值,默认去除字符窜左右两边的空格 print(msg.strip('* '))#指定要去除的字符后必须加空格,多个需过滤的字符也以空格分开 print(msg.strip('* / , h '))# 去除多个字符以空格隔开,(不去除的整体字符窜中的指定字符) # 切分字符窜split:把一个字符窜按照某种分隔符切成一个列表 info = "username1:user:pwd:00 user:/user:/bin:/path" res = info.split(':',maxsplit=-1)#指定按“:”切分,maxsplit指定切分次数,-1为不限制 print(res,type(res)) info2 = "hello test.txt 22" res = info2.split()#不指定切分字符,则按空格切分 print(res,type(res)) res2 = info2.split(' ',maxsplit=1)# maxsplit=1,只切分一次 print(res2,type(res2)) #把列表切分为字符窜 res = ['username1', '100', '/path'] print(res,type(res))# 字符窜 list_string = ':'.join(res)#把列表切分为字符窜(前提是 列表中所有元素都是字符窜) print(list_string,type(list_string)) #循环取值 msg = 'hello world' i=0 while i < len(msg): print(msg[i]) #依赖索引取值 i+=1 #for 循环取值 msg = 'hello world' for item in msg: #不依赖索引取值,常用的取值方式,可以取所有类型的值(如:list、dict) print(item) #for +break #for +continue

 

posted @ 2019-10-14 00:03  sunny.boy  阅读(613)  评论(0编辑  收藏  举报