3-4:字符串方法

find:在一个较长的字符串中查找子串,返回子串所在位置的最左端索引;

方法可以指定起始点和结束点参数。

join:是split方法的逆方法,用来连接序列中的元素。

lower:返回字符串的小写字母版;title返回单词的首字母大写;

capwords函数返回单词的首字母大写,但是需要从string模块中先导入。

replace:返回某字符串的所有匹配项均被替换之后得到的字符串。

split:用来将字符串分割成序列。

strip:返回去除两侧(不包括内部)空格的字符串。

translate:替换字符串中的某些部分,只处理单个字符,优势:同时进行多个替换,效率高。

maketrans函数:将第一个字符串中的每个字符都用第二个字符串中相同位置的字符替换。

例子:

 1 #!/usr/bin/env python
 2 #-*- coding:utf-8 -*-
 3 #1.find
 4 a='with a moo-moo here,and a moo-moo there'
 5 print a.find('moo')
 6 print a.find('moo',8,16)
 7 print a.find('moo',20,30)
 8 print a.find('here')
 9 print a.find('wit')
10 print a.find('wth')
11 print a.count('moo')
12 #2.join
13 b=['1','2','3','4','5']
14 b1='+'
15 b2=b1.join(b)
16 print b2
17 b3=' ','usr','bin','env'
18 b4='/'
19 b5='C:'
20 b6=b4.join(b3)
21 b7=b5+'\'.join(b3)
22 print b6
23 print b7
24 #3.lower
25 import string
26 c='Beginning Python From Novice to Professional second Edition'
27 print c.lower()
28 print c.title()
29 print string.capwords(c)
30 #4.replace
31 d=c.replace('second','third')
32 print d
33 #5.split
34 e=b2.split('+')
35 e1=b2.split('3')
36 print e
37 print e1
38 #6.strip
39 f='  '+c+'  1  '
40 print f
41 print f.strip()
42 f1='@###$$$!'+c+'***'
43 print f1
44 print f1.strip('@')
45 print f1.strip('@#*')
46 #7.translate
47 from string import maketrans
48 g=maketrans('cs','kz')
49 print len(g)
50 g1=maketrans('c','c')
51 print g1
52 print g[97:123]
53 print g[0:96]
54 print g1.find('a')
55 print g1.find('A')
56 print c.translate(g)

效果:

 1 7
 2 11
 3 26
 4 15
 5 0
 6 -1
 7 4
 8 1+2+3+4+5
 9  /usr/bin/env
10 C: usrinenv
11 beginning python from novice to professional second edition
12 Beginning Python From Novice To Professional Second Edition
13 Beginning Python From Novice To Professional Second Edition
14 Beginning Python From Novice to Professional third Edition
15 ['1', '2', '3', '4', '5']
16 ['1+2+', '+4+5']
17   Beginning Python From Novice to Professional second Edition  1  
18 Beginning Python From Novice to Professional second Edition  1
19 @###$$$!Beginning Python From Novice to Professional second Edition***
20 ###$$$!Beginning Python From Novice to Professional second Edition***
21 $$$!Beginning Python From Novice to Professional second Edition
22 256
23 
24 
25 
26  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~
27 
28                                                                                                 abkdefghijklmnopqrztuvwxyz
29 
30 
31 
32  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_
33 97
34 65
35 Beginning Python From Novike to Profezzional zekond Edition

小知识:split('3')将字符串‘1+2+3+4+5’分成了'1+2+‘和’4+5‘两个字符串放入序列中。

原文地址:https://www.cnblogs.com/scholarly/p/10234155.html