Source From Here
Question
I have this code (printing the occurrence of the all permutations in a string):
I want to print all the permutation occurrence there is in string varaible. since the permutation aren't in the same length i want to fix the width and print it in a nice not like this one:
How can I use format to do it?
How-To
This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax. You can use string formatting like this:
Basically:
If you are using format function from string class:
In your specific case a possible implementation could look like:
SIDE NOTE: Just wondered if you are aware of the existence of the itertools module. For example you could obtain a list of all your combinations in one line with:
Question
I have this code (printing the occurrence of the all permutations in a string):
- 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
How-To
This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax. You can use string formatting like this:
- >>> print("|%5s" % 'aa')
- | aa
- >>> print("%5s" % 'aaa')
- | aaa
- >>> print("%5s" % 'aaaa')
- | aaaa
- >>> print("%5s" % 'aaaaa')
- |aaaaa
If you are using format function from string class:
- >>> print("{:^>5s}".format('a')) # '^ 'as filler; '>' as align policy; '5' as width
- ^^^^a
- >>> print("{:^>5s}".format('aa'))
- ^^^aa
- >>> print("{:^>5s}".format('aaa'))
- ^^aaa
- >>> print("{:^>5s}".format('aaaa'))
- ^aaaa
- >>> print("{:^>5s}".format('aaaaa'))
- aaaaa
- >>> 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
- >>> import itertools as it
- >>> it.permutations(['a', 'b'], 1)
沒有留言:
張貼留言