How to print a line with a fixed width?

I have this code (print the appearance of 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)); 

I want to print all permutation occurrences in a varaible string.

since the permutation is not in the same length, I want to fix the width and print it in a good one, not like this:

 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 can I use format for this?

I found these messages, but this did not match the alphanumeric strings:

python fixed string formatting width

Setting fixed length using python

+92
python format
Dec 09 '11 at 19:10
source share
5 answers

EDIT 2013-12-11 - This answer is very old. This is still true and correct, but people looking at it should prefer the new format syntax .

You can use string formatting as follows:

 >>> print '%5s' % 'aa' aa >>> print '%5s' % 'aaa' aaa >>> print '%5s' % 'aaaa' aaaa >>> print '%5s' % 'aaaaa' aaaaa 

Basically:

  • the % character tells Python that it should replace something with a token
  • the s character tells python that the token will be a string
  • 5 (or any other desired number) informs Python of the need to pad the string with spaces of up to 5 characters.

In your particular case, a possible implementation might look like this:

 >>> 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 

Side note: just wondering if you know about the existence of the itertools module . For example, you can get a list of all your combinations on one line with:

 >>> [''.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'] 

and you can get the number of occurrences using combinations in combination with count() .

+99
Dec 09 '11 at 19:13
source share

I find using str.format much more elegant:

 >>> '{0: <5}'.format('ss') 'ss ' >>> '{0: <5}'.format('sss') 'sss ' >>> '{0: <5}'.format('ssss') 'ssss ' >>> '{0: <5}'.format('sssss') 'sssss' 

If you want to align the string to the right, use > instead of < :

 >>> '{0: >5}'.format('ss') ' ss' 

Edit: As mentioned in the comments: 0 indicates the index in the list of format arguments.

+175
Apr 16 '13 at 21:32
source share

Originally posted as an answer to question @ 0x90, but it was rejected for deviating from the original original intent and recommended posting it as a comment or answer, so I am including a short entry here.

In addition to the answer from @ 0x90, the syntax can be made more flexible using a width variable (according to the comment by @ user2763554):

 width=10 '{0: <{width}}'.format('sss', width=width) 

In addition, you can make this expression more concise by using only numbers and relying on the order of the arguments passed in format :

 width=10 '{0: <{1}}'.format('sss', width) 

Or even leave all numbers for maximum, potentially non-pythonic implicit compactness:

 width=10 '{: <{}}'.format('sss', width) 



Update 2017-05-26

With the introduction of formatted string literals ("short strings") in Python 3.6, you can now access previously defined variables with stronger syntax:

 >>> name = "Fred" >>> f"He said his name is {name}." 'He said his name is Fred.' 

This also applies to string formatting.

 >>> width=10 >>> string = 'sss' >>> f'{string: <{width}}' 'sss ' 
+54
Jan 07 '17 at 16:22
source share

format is by far the most elegant way, but afaik you cannot use this with the logging python module, so here you can do it with % formatting:

 formatter = logging.Formatter( fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s', ) 

Here, - indicates left justification, and a number before s indicates a fixed width.

Some sample results:

 2017-03-14 14:43:42,581 | this-app | INFO | running main 2017-03-14 14:43:42,581 | this-app.aux | DEBUG | 5 is an int! 2017-03-14 14:43:42,581 | this-app.aux | INFO | hello 2017-03-14 14:43:42,581 | this-app | ERROR | failed running main 

More info in the docs: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

+7
Mar 14 '17 at 18:49
source share

try using the following expression as a template

 def aaa(i): return i*10/2 for i in range(5): print('{:>50}{:>20}:{:>20.4f}'.format('Value of aaa function for i=',10**i, aaa(10**i))) Value of aaa function for i= 1: 5.0000 Value of aaa function for i= 10: 50.0000 Value of aaa function for i= 100: 500.0000 Value of aaa function for i= 1000: 5000.0000 Value of aaa function for i= 10000: 50000.0000 
0
Jan 23 '19 at 14:10
source share



All Articles