Python 几个字符串常用的方法
来源:互联网 发布:mac顶部菜单栏截图工具 编辑:程序博客网 时间:2024/05/22 07:01
1.find方法,在有个较长的查找子串,返回子串所在位置的最左端索引,如果没有找到子串则返回-1
>>> str='Monty Python\'s Flying Cirus'>>> str.find('Mon')0>>> str.find('ing')18>>> str.find('an')-12.lower方法,返回字符串的小写字母版
>>> str='GhdaHJKdjjaADD'>>> str.lower()'ghdahjkdjjaadd'3.join方法,使用方法b.join(a),其中a,b都是字符串类型(b可以是序列或者列表,但是元素需要是字符串类型),表示a中元素用b来链接
>>> d=list('12345')>>> d['1', '2', '3', '4', '5']>>> '+'.join(d)'1+2+3+4+5'>>> f=('','user','bin','env')>>> g='\\'>>> print 'C:' + g.join(f)C:\user\bin\env4.replace方法,返回某字符串的所有匹配项均被替换后的字符串 (有没有想到word里面的替换字符)
>>> str1='this is a dog!'>>> str1.replace('is','at')'that at a dog!'5.split方法,join的逆方法,将字符串分割为序列
>>> str1 = '+'.join(list('12345'))>>> str1'1+2+3+4+5'>>> str1.split('+')['1', '2', '3', '4', '5']>>> str2='this is a dog!'>>> str2.split() #不指明分割符号时,默认用空格做分隔符['this', 'is', 'a', 'dog!']6.strip方法,返回去除两侧空格的字符串(中间空格保留的哦) (做输入校验比对字符串很有用)
>>> str=' this is a dog! '>>> str' this is a dog! '>>> str.strip()'this is a dog!'>>>>>> str.strip('t !') #指定去掉两边的三种字符:t 空格 !'his is a dog'
7.translate方法,处理单个字符的替换,不过有点在于可以同时进行多个字符的替换str1='abcdefghigklmnopqrstuvwxyz'table=maketrans('az','za') #maketrans表示把第一个字符串的每个字符都用第二个字符串的同位字符替换print str1.translate(table)str2='$'.join(str1)print str2print str2.translate(table,'bcd$') #translate方法的第二个可选参数,删除指定字符上面三行输出如下:
zbcdefghigklmnopqrstuvwxya #z变成了a,a变成了za$b$c$d$e$f$g$h$i$g$k$l$m$n$o$p$q$r$s$t$u$v$w$x$y$zzefghigklmnopqrstuvwxya ##z变成了a,a变成了z,并且所有的字符"bcd$"都被删除了
阅读全文
0 0
- Python 几个字符串常用的方法
- 字符串常用的几个方法
- Java字符串处理的几个常用方法
- Java字符串处理的几个常用方法
- 常用的Python字符串方法
- Python字符串的常用方法
- 几个Python字符串方法浅析
- Python字符串常用方法
- python常用字符串方法
- Python 字符串常用方法
- python 字符串常用方法
- C常用的对字符串操作的几个方法
- python中字符串的常用方法
- Python对字符串的常用处理方法
- Python中字符串常用的方法
- Python字符串中常用的方法
- JavaScript中字符串最常用的几个方法
- 几个常用的方法
- R
- 设计模式笔记(二)设计六大原则之二--里氏替换原则
- leetcode 27 题解 翻译 Python版
- 11月6日 哈工大c语言编程题
- ImageNet Classification with Deep Convolutional Networks
- Python 几个字符串常用的方法
- Codeforces Round #350 (Div. 2) B
- bp神经网络
- 11.06笔记整理、作业以及学习心得
- java IO 管道流 PipedInputStream 使这2个线程互相通讯
- xlib一夜学习体会
- Hibernate--继承映射详解
- Oracle Application Express by Design.pdf 英文原版 免费下载
- 关于Unable to instantiate Action, xxxAction, defined for 'xxx' in namespace '/'xxxAction解决方案