首页 > 编程语言 > 详细

python基础技巧综合训练题1

时间:2018-03-31 00:30:52      阅读:337      评论:0      收藏:0      [点我收藏+]

1,大小写翻转

>>> str=‘hello,GhostWU‘
>>> str.swapcase()
‘HELLO,gHOSTwu‘

2,从一串字符串中,提取纯数字组合

>>> str="adfask22jkljhh3jkljhgh435"
>>> ‘‘.join( [s for s in str if s.isdigit() ] )
‘223435‘
>>> 

等价于:

>>> str="adfask22jkljhh3jkljhgh435"
>>> l = []
>>> for s in str:
...     if s.isdigit():
...             l.append( s )
... 
>>> l
[‘2‘, ‘2‘, ‘3‘, ‘4‘, ‘3‘, ‘5‘]
>>> ‘‘.join( l )
‘223435‘
>>> 

 3,统计字符的出现次数,以字符为键,大小写视为相同字符

>>> s = "abcsABCDEFabcAbcdFEA"
>>> s = s.lower()
>>> s
‘abcsabcdefabcabcdfea‘
>>> res = dict( [ ( key, s.count( key ) ) for key in set( s ) ] )
>>> res
{‘a‘: 5, ‘c‘: 4, ‘b‘: 4, ‘e‘: 2, ‘d‘: 2, ‘f‘: 2, ‘s‘: 1}
>>> 

4,字符串去重,按原来的顺序输出

>>> s
‘abcccabdefdx‘
>>> l = list( s )
>>> set_list = list( set( l ) )
>>> res = set_list.sort( key=l.index )
>>> res
>>> set_list
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘x‘]
>>> 

 5,字符串反转

>>> s = ‘abc‘
>>> s[::-1]
‘cba‘

6,去除字符串中的数字,然后排序,如果出现相同的字母,如aA,大写字母排在小写字母的前面

#!/usr/bin/python
#coding:utf-8

s = ‘abcDBA233ABC1‘
l = sorted( s )

upper_list = []
lower_list = []

for v in l:
    if v.isupper():
        upper_list.append( v )
    elif v.islower():
        lower_list.append( v )
    else:
        pass

#print upper_list, lower_list

for x in upper_list:
    x_lower = x.lower()
    if x_lower in lower_list:
        lower_list.insert( lower_list.index( x_lower ), x )

print ‘‘.join( lower_list )

 

python基础技巧综合训练题1

原文:https://www.cnblogs.com/ghostwu/p/8646404.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!