2018年10月27日 星期六

[ Python 常見問題 ] How to format print output or string into fixed width?

Source From Here 
Question 
I have this code (printing the occurrence of the all permutations in a string): 
  1. def splitter(str):  
  2.     for i in range(1, len(str)):  
  3.         start = str[0:i]  
  4.         end = str[i:]  
  5.         yield (start, end)  
  6.         for split in splitter(end):  
  7.             result = [start]  
  8.             result.extend(split)  
  9.             yield result      
  10.   
  11. el =[];  
  12.   
  13. string = "abcd"  
  14. for b in splitter("abcd"):  
  15.     el.extend(b);  
  16.   
  17. unique =  sorted(set(el));  
  18.   
  19. for prefix in unique:  
  20.     if prefix != "":  
  21.         print "value  " , prefix  , "- num of occurrences =   " , string.count(str(prefix));  
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: 
  1. value   a - num of occurrences =    1  
  2. value   ab - num of occurrences =    1  
  3. value   abc - num of occurrences =    1  
  4. value   b - num of occurrences =    1  
  5. value   bc - num of occurrences =    1  
  6. value   bcd - num of occurrences =    1  
  7. value   c - num of occurrences =    1  
  8. value   cd - num of occurrences =    1  
  9. value   d - num of occurrences =    1  
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: 
  1. >>> print("|%5s" % 'aa')  
  2. |   aa  
  3. >>> print("%5s" % 'aaa')  
  4. |  aaa  
  5. >>> print("%5s" % 'aaaa')  
  6. | aaaa  
  7. >>> print("%5s" % 'aaaaa')  
  8. |aaaaa  
Basically: 
* the % character informs python it will have to substitute something to a token 
* the s character informs python the token will be a string 
* the 5 (or whatever number you wish) informs python to pad the string with spaces up to 5 characters.

If you are using format function from string class: 
  1. >>> print("{:^>5s}".format('a'))  # '^ 'as filler; '>' as align policy; '5' as width  
  2. ^^^^a  
  3. >>> print("{:^>5s}".format('aa'))  
  4. ^^^aa  
  5. >>> print("{:^>5s}".format('aaa'))  
  6. ^^aaa  
  7. >>> print("{:^>5s}".format('aaaa'))  
  8. ^aaaa  
  9. >>> print("{:^>5s}".format('aaaaa'))  
  10. aaaaa  
In your specific case a possible implementation could look like: 
  1. >>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}  
  2. >>> for item in dict_.items():  
  3. ...     print 'value %3s - num of occurances = %d' % item # %d is the token of integers  
  4. ...   
  5. value   a - num of occurances = 1  
  6. value  ab - num of occurances = 1  
  7. value abc - num of occurances = 1  
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: 
  1. >>> import itertools as it  
  2. >>> it.permutations(['a', 'b'], 1)  
  3.  0x7f8994e3e470>  
  • >>> list(it.permutations(['a', 'b'], 1))  
  • [('a',), ('b',)]  
  • >>> list(it.permutations(['a', 'b'], 2))  
  • [('a', 'b'), ('b', 'a')]  
  • >>> [''.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', ...]  


  • 沒有留言:

    張貼留言

    [Git 常見問題] error: The following untracked working tree files would be overwritten by merge

      Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...