如何在Python中按字母顺序排列string中的字母
有没有一种简单的方法来按字母顺序排列Python中的字母?
因此对于:
a = 'ZENOVW' 我想返回:
 'ENOVWZ' 
	
你可以做:
 >>> a = 'ZENOVW' >>> ''.join(sorted(a)) 'ENOVWZ' 
 >>> a = 'ZENOVW' >>> b = sorted(a) >>> print b ['E', 'N', 'O', 'V', 'W', 'Z'] 
  sorted返回一个列表,所以你可以再次使用join使它成为一个string: 
 >>> c = ''.join(b) 
 它将b的项目连同每个项目之间的空string''连接在一起。 
 >>> print c 'ENOVWZ' 
Sorted()解决scheme可以给你一些意想不到的结果与其他string。
其他解决scheme列表:
对信件进行分类并使其明确:
 >>> s = "Bubble Bobble" >>> ''.join(sorted(set(s.lower()))) ' belou' 
对字母进行sorting,并在保持大写字母的同时,
 >>> s = "Bubble Bobble" >>> ''.join(sorted(set(s))) ' Bbelou' 
sorting字母并保留重复项:
 >>> s = "Bubble Bobble" >>> ''.join(sorted(s)) ' BBbbbbeellou' 
如果你想摆脱结果中的空间,在任何这些情况下添加strip()函数:
 >>> s = "Bubble Bobble" >>> ''.join(sorted(set(s.lower()))).strip() 'belou'