现在的位置: 首页 > 综合 > 正文

001_001 Python字符串一个个遍历

2017年12月10日 ⁄ 综合 ⁄ 共 759字 ⁄ 字号 评论关闭

代码如下:

#coding=utf-8
print '中国'


#每次处理一个字符串
mystr = u'test string中国'


#方案一 使用list
liststr = list(mystr)


for i in liststr:
    print '1-',i
    
print liststr.__len__()
print liststr[12]


#方案二 使用for
for i in mystr:
    print '2-',i
    
#方案三使用列表推导
def fun_print(c):
    print '3-',c
    
res = [fun_print(c) for c in mystr]


#方案四使用map
def fun_printmap(c):
    print '4-',c
resmap = map(fun_printmap,mystr)




#other
import sets    #导入集合
left = sets.Set('abcabc')      
right = sets.Set('abcdefabcdef')
print left
print right
print left & right #交集
print left | right #并集
print ' '.join(left &right)

打印结果如下:

中国
1- t
1- e
1- s
1- t
1-  
1- s
1- t
1- r
1- i
1- n
1- g
1- 中
1- 国
13

2- t
2- e
2- s
2- t
2-  
2- s
2- t
2- r
2- i
2- n
2- g
2- 中
2- 国
3- t
3- e
3- s
3- t
3-  
3- s
3- t
3- r
3- i
3- n
3- g
3- 中
3- 国
4- t
4- e
4- s
4- t
4-  
4- s
4- t
4- r
4- i
4- n
4- g
4- 中
4- 国
Set(['a', 'c', 'b'])
Set(['a', 'c', 'b', 'e', 'd', 'f'])
Set(['a', 'c', 'b'])
Set(['a', 'c', 'b', 'e', 'd', 'f'])
a c b

抱歉!评论已关闭.