python--字符串
字符串是不可变对象,有序的字符集合,字符序列 ,Python3起,字符串就是Unicode类型
join连接:
"x".join(iterable) -> str 将可迭代对象连接起来,使用x作为分隔符 , 可迭代对象本身元素都是字符串 ,返回一个新字符串
字符串分割split:
split(sep=None, maxsplit=-1) -> list of strings 从左至右 (rsplit从右向左), sep 指定分割字符串,缺省的情况下空白字符串作为分隔符 ,maxsplit 指定分割的次数,-1 表示遍历整个字符串
print('abc'.split('b'))=>['a','c']
splitlines([keepends]) -> list of strings 按照行来切分字符串 ,keepends 指的是是否保留行分隔符 ,行分隔符包括\n、\r\n、\r等
字符串分割partition:
partition(sep) -> (head, sep, tail) 从左至右(rpartition从右向左),遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾三部分的三元组;如果 没有找到分隔符,就返回头、2个空元素的三元组 , sep 分割字符串,必须指定
print('abc'.partition('b'))=>('a', 'b', 'c')
upper()全大写、lower()全小写,swapcase()交互大小写
字符串修改:
replace(old, new[, count]) -> str 字符串中找到匹配替换为新子串,返回新字符串 , count表示替换几次,不指定就是全部替换
p strip([chars]) -> str 从字符串两端去除指定的字符集chars中的所有字符 , 如果chars没有指定,去除两端的空白字符
字符串查找:
find(sub[, start[, end]]) -> int 在指定的区间[start, end),从左至右(rfind从右向左),查找子串sub。找到返回索引,没找到返回-1
index(sub[, start[, end]]) -> int 在指定的区间[start, end),从左至右,查找子串sub。找到返回索引,没找到抛出异常ValueError
count(sub[, start[, end]]) -> int 在指定的区间[start, end),从左至右,统计子串sub出现的次数
时间复杂度 index和count方法都是O(n) ,随着列表数据规模的增大,而效率下降
字符串判断:
endswith(suffix[, start[, end]]) -> bool 在指定的区间[start, end),字符串是否是suffix结尾
startswith(prefix[, start[, end]]) -> bool 在指定的区间[start, end),字符串是否是prefix开头
字符串格式化:
print("{server} {1}:{0}".format(8888, '192.168.1.100', server='Web Server Info : '))=>Web Server Info : 192.168.1.100:8888
print("{0[0]}.{0[1]}".format(('coode','online')))=>coode.online
print('{0}*{1}={2:<2}'.format(3,2,2*3))=>3*2=6
print('{0}*{1}={2:<02}'.format(3,2,2*3))=>3*2=60
print('{0}*{1}={2:>03}'.format(3,2,2*3))=>3*2=006
浙公网安备 33010602011771号