1 # -*- coding: utf-8 -*-
 2 """
 3  合并字符串
 4  
 5  涉及的函数
 6  join():性能优于+操作
 7  formatString % (pieces):对于少量字符串(尤其是变量中的
 8  字符串),需要拼接,或者还需要加入额外的信息,该方法较好
 9  %s暗中帮我们做了很多工作,如调用str方法,还能指定浮点数的
10  输出有效位数
11  +:不要用它来创建大的字符串,psyco编译器可大幅降低+=的性能损失
12  operator.add
13  
14  python字符串无法改变,对字符串的操作将产生一个新的对象
15  拼接N个字符串将舍弃N-1个中间的结果
16  但不创建结果,可能提高性能,但是往往不能一步到位得到结果
17  
18  
19 """
20 # 字符串list的拼接
21 strList = ['abc','edf','ghi']
22 
23 joinStrList = ''.join(strList)
24 print joinStrList
25 # Output:abcedfghi
26 joinStrListWithDot = ','.join(strList)
27 print joinStrListWithDot
28 # Output:abc,edf,ghi
29 joinStrListWithDotSpace = ', '.join(strList)
30 print joinStrListWithDotSpace
31 # Output:abc, edf, ghi
32 
33 # 变量中字符串的拼接
34 smallStr1 = 'Good'
35 smallStr2 = ' Good'
36 smallStr3 = ' Study'
37 smallStr4 = 'Day Day Up!'
38 varStr = '%s%s%s,%s' % (smallStr1, smallStr2, smallStr3, smallStr4)
39 print varStr
40 
41 # + 也可以拼接
42 plusSignStr = smallStr1 + smallStr2 + smallStr3
43 print plusSignStr
44 # Output:Good Good Study
45 
46 strList = ['abc','edf','ghi','jkl']
47 plusSignStrFor = ''
48 
49 for piece in strList:
50     plusSignStrFor += piece
51 print plusSignStrFor
52 # Output: abcedfghijkl
53 
54 # 更加紧凑和漂亮的方式
55 import operator
56 opStr = reduce(operator.add,strList,'')
57 print opStr
58 # Output: abcedfghijkl

 

posted on 2014-06-18 15:35  cpycpp  阅读(291)  评论(0编辑  收藏  举报