小点总结
字符串:
1.可以装换为其他任意类型:列表,元组,集合
2.可以索引取值,但是不能用值:
a='hello python'
print(a[0],type(a[0])) #h <class 'str'>
b=a[0]
print(b) #h
a[1]='a' #'str' object does not support item assignment
3.可以切片
4、可使用len()方法 判断其字符串长度时,包括字符串之间的空格
5、成员运算in not in
6、移除空白 strip rstrip lstrip
7、切分字符串为列表 split
8.产生新的字符串 'sep'.join(sep)
'sep'指的是分隔符,可以为空;(sep)指的是要连接的元素序列:字符串、字典、元组、列表、集合
小点:若对字典操作,得到的是只带有含指定连接符的key的列表
9、可以for循环
10.字符串的大小写 .upper() .lower() .title()
11.判定是否是指定前缀开头 ,后缀开头
str.startswith(str, beg=0,end=len(string)); 指定前缀
string.endswith(str, beg=[0,end=len(string)]) :
string[beg:end].endswith(str) 指定后缀
string: 被检测的字符串
str: 指定的字符或者子字符串(可以使用元组,会逐一匹配)
beg: 设置字符串检测的起始位置(可选,从左数起)
end: 设置字符串检测的结束位置(可选,从左数起)
如果存在参数 beg 和 end,则在指定范围内检查,否则在整个字符串中检查
12.字符串格式化 .format()方法
用法:通过{}来代替传统%方式
>>> 'my name is {} ,age {}'.format('hoho',18)
'my name is hoho ,age 18'
'my name is {1} ,age {0}'.format(10,'hoho')
'my name is hoho ,age 10'
'my name is {} ,age {}'.format(*li) #此时用*list 将列表里的元素分配出来
'my name is hoho ,age 18 #传入位置参数列表可用*列表
13. split() 通过指定分隔符对字符串进行切片,装换成列表 ,如果参数 num 有指定值,则分隔 num+1 个子字符串 通过这种方法不改变原先的字符串
str.split(str="", num=string.count(str))
u="www.doiido.com" #使用默认空格符来分割,不指定的话,以空格分割。 print(u.split()) #输出结果为: ['www.doiido.com'] #以‘.’为分割符 print(u.split('.')) #输出结果: ['www', 'doiido', 'com']
14.replace()
方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
14.isdigit() 检测字符串是否只由数字组成。
print('123123'.isdigit()) # 如果字符串是由纯数字组成的,则返回True
print('123123 '.isdigit()) #此时存在空格,返回False
15.count 用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置
str.count(sub, start= 0,end=len(string))
- sub -- 搜索的子字符串
- start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
- end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
print('123 ke123ke'.count('ke',0,6))
输出为 1
字典
posted on 2019-03-26 21:42 michael-chang 阅读(98) 评论(0) 收藏 举报
浙公网安备 33010602011771号