我有这段代码(在字符串中打印所有排列的出现)
def splitter(str):
for i in range(1, len(str)):
start = str[0:i]
end = str[i:]
yield (start, end)
for split in splitter(end):
result = [start]
result.extend(split)
yield result
el =[];
string = "abcd"
for b in splitter("abcd"):
el.extend(b);
unique = sorted(set(el));
for prefix in unique:
if prefix != "":
print "value " , prefix , "- num of occurrences = " , string.count(str(prefix));
我想打印字符串可变项中所有出现的排列。
由于排列的长度不同,因此我想固定宽度并以一种不太好的方式打印它:
value a - num of occurrences = 1
value ab - num of occurrences = 1
value abc - num of occurrences = 1
value b - num of occurrences = 1
value bc - num of occurrences = 1
value bcd - num of occurrences = 1
value c - num of occurrences = 1
value cd - num of occurrences = 1
value d - num of occurrences = 1
如何使用
format
做到这一点?我找到了这些帖子,但与字母数字字符串的配合并不理想:
python string formatting fixed width
Setting fixed length with python
最佳答案
编辑2013-12-11 -这个答案很老。它仍然是有效和正确的,但是关注此问题的人们应该更喜欢new format syntax。
您可以像这样使用string formatting:
>>> print '%5s' % 'aa'
aa
>>> print '%5s' % 'aaa'
aaa
>>> print '%5s' % 'aaaa'
aaaa
>>> print '%5s' % 'aaaaa'
aaaaa
基本上:
%
字符通知python,它将不得不用某种东西代替 token s
字符通知python token 将是字符串5
(或您想要的任何数字)通知python使用最多5个字符的空格填充字符串。 在您的特定情况下,可能的实现可能类似于:
>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
... print 'value %3s - num of occurances = %d' % item # %d is the token of integers
...
value a - num of occurances = 1
value ab - num of occurances = 1
value abc - num of occurances = 1
侧面注意:只是想知道您是否知道
itertools
module的存在。例如,您可以使用以下命令在一行中获取所有组合的列表:>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']
并且可以通过将
combinations
与count()
结合使用来获得出现的次数。