字符串的的方法很多,只能学一些常用的,需要时再去查资料了。
方法center通过向字符串两边添加填充字符,让字符串居中,一般默认填充空格。 >>> 'The Middle by Jimmy Eat World'.center(43)' The Middle by Jimmy Eat World '>>> 'The Middle by Jimmy Eat World'.center(43,'*')'*******The Middle by Jimmy Eat World*******'
方法find在字符串中查找子串,若字符串中存在,则返回第一个字符的索引,否则返回-1。 >>> title = 'Monty Python's Flying Circus'>>> title.find('Monty')0>>> title.find('Python')6>>> title.find('Flying')15>>> title.find('Zir')-1 还可以指定搜索的起点和终点,起点和终点值指定的是搜索范围,包含起点,不包含终点。 >>> subject = '$$$ Get rich now!!! $$$'>>> subject.find('$$$')0>>> subject.find('$$$',1) #只指定起点20>>> subject.find('!!!')16>>> subject.find('!!!',0,16) #同时指定起点和终点-1
方法join,用于合并序列元素,所合并的序列必须都是字符串。 >>> seq = [1,2,3,4,5]>>> sep = '+'>>> sep.join(seq)Traceback (most recent call last): File '', line 1, in
方法lower将字符串内所有字符小写。 >>> 'Trondheim Hammer Dance'.lower()'trondheim hammer dance' 如果用户名不区分大小写,用这个方法,在存储和搜索时,将所有用户名转换为小写。 >>> name = 'Gumby'>>> names = ['gumby','smith','jones']>>> if name.lower() in names:... print('Fount it!')... Fount it! 相反,如果将所有字符转换成大写则使用upper() >>> 'Hello,world!'.upper()'HELLO,WORLD!'
方法replace将指定的子串替换为另一个字符串,并返回替换结果。这个方法类似“查找并替换”功能。 >>> 'This is a test'.replace('is','eez')'Theez eez a test' 参考书籍《Python基础教程(第3版)》 |
|
来自: 昵称11935121 > 《未命名》