177

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

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:

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 to do it?

I found these posts but it didn't go well with alphanumeric strings:

python string formatting fixed width

Setting fixed length with python

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
0x90
  • 39,472
  • 36
  • 165
  • 245

8 Answers8

295

I find using str.format much more elegant:

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

In case you want to align the string to the right use > instead of <:

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

Edit 1: As mentioned in the comments: the 0 in '{0: <5}' indicates the argument’s index passed to str.format().


Edit 2: In python3 one could use also f-strings:

sub_str='s'
for i in range(1,6):
    s = sub_str*i
    print(f'{s:>5}')
    
'    s'
'   ss'
'  sss'
' ssss'
'sssss'

or:

for i in range(1,5):
    s = sub_str*i
    print(f'{s:<5}')
's    '
'ss   '
'sss  '
'ssss '
'sssss'

of note, in some places above, ' ' (single quotation marks) were added to emphasize the width of the printed strings.

0x90
  • 39,472
  • 36
  • 165
  • 245
  • 6
    Additionally, the 0 indicates the position of the format argument, so you can do two other things: `'{<5}'.format('ss')` `'ss '` just like before, but without the 0, does the same thing or `'Second {1: <5} and first {0: <5}'.format('ss', 'sss')` `'Second sss and first ss '` so you can reorder or even output the same variable many times in a single output string. – mightypile Dec 23 '13 at 17:59
  • 17
    I can no longer edit the previous comment, which needs it. `{<5}` does not work, but `{: <5}` does work without the index value. – mightypile Dec 23 '13 at 18:45
  • 13
    Here's the Python [Format Specification Mini-Language](https://docs.python.org/2/library/string.html#format-specification-mini-language) describing these format strings and additional options. For quick reference, the space in `{0: <5}` is the `[fill]` , the `<` is `[align]`, and `5` is `[width]` – cod3monk3y Nov 23 '14 at 06:08
  • 5
    That 5 can be a variable substitution `>>> print width 20 >>> print "{0: <{width}}".format("ssssss", width=width).split('\n') ['ssssss '] >>>` – gjois Nov 04 '16 at 11:16
  • 7
    You can also use numbers and just list the variables in order `width=10; "{0: <{1}}".format('sss', width)`. Or even leave out the numbers `'{: <{}}'.format('sss', width)` – joelostblom Jan 07 '17 at 14:42
  • 1
    @cheflo please feel welcome to edit the answer itself. Thank you – 0x90 Jan 07 '17 at 14:45
  • @cod3monk3y if i am not wrong, `{0: <5}` the `0` means the first argument but what dose `:` do in here? And I can't find the role of `:` in the [format-specification](https://docs.python.org/2/library/string.html#format-specification-mini-language) – Ziu May 08 '17 at 12:27
  • The colon separates the argument `{0}` from the formatting of that argument. It's optional. See `format_spec` in the [Format String Syntax](https://docs.python.org/2/library/string.html#formatstrings). From the docs: "The field_name is optionally followed by ... a format_spec, which is preceded by a colon ':'." – cod3monk3y May 09 '17 at 14:37
140

EDIT 2013-12-11 - 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

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.

In your specific case a possible implementation could look like:

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

>>> [''.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 could get the number of occurrences by using combinations in conjunction with count().

phoenix
  • 7,988
  • 6
  • 39
  • 45
mac
  • 42,153
  • 26
  • 121
  • 131
  • 30
    You should perhaps mention that negative numbers give left-justified padded output; this is hardly intuitive for a beginner. – tripleee Oct 14 '12 at 06:27
  • +1 for @tripleee, without your negative numbers give left-justified comment I would have been hitting my head longer... thx m8. – Brian Wylie Jan 17 '14 at 23:27
  • This is far more intuitive and concise than the new str.format. I don't understand why there is this push in python towards convolution – scottmrogowski Jun 06 '14 at 00:39
  • Is there a way to fill in the blank spaces with a specific character? For example, if we need to print "05" instead of " 5" – Harshit Jindal Jun 09 '18 at 18:10
  • 2
    Here are some more tricks for elegant fixed-width printing with f-strings on [Medium](https://medium.com/@NirantK/best-of-python3-6-f-strings-41f9154983e). – pfabri Sep 22 '19 at 17:27
110

Originally posted as an edit to @0x90's answer, but it got rejected for deviating from the post's original intent and recommended to post as a comment or answer, so I'm including the short write-up here.

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

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

Further, you can make this expression briefer, by only using numbers and relying on the order of the arguments passed to format:

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

Or even leave out all numbers for maximal, potentially non-pythonically implicit, compactness:

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

Update 2017-05-26

With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to access previously defined variables with a briefer 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       '
joelostblom
  • 43,590
  • 17
  • 150
  • 159
13

format is definitely the most elegant way, but afaik you can't use that with python's logging module, so here's how you can do it using the % formatting:

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

Here, the - indicates left-alignment, and the number before s indicates the fixed width.

Some sample output:

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 at the docs here: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

ryantuck
  • 6,146
  • 10
  • 57
  • 71
  • 1
    This won't shorten strings above 20 characters however. Use `'%(name)20.20s'` which sets 20 both as min and max string length! – xjcl Feb 21 '20 at 21:44
9

This will help to keep a fixed length when you want to print several elements at one print statement.

25s formats a string with 25 spaces, left justified by default.

5d formats an integer reserving 5 spaces, right justified by default.

members=["Niroshan","Brayan","Kate"]
print("__________________________________________________________________")
print('{:25s} {:32s} {:35s} '.format("Name","Country","Age"))
print("__________________________________________________________________")
print('{:25s} {:30s} {:5d} '.format(members[0],"Srilanka",20))
print('{:25s} {:30s} {:5d} '.format(members[1],"Australia",25))
print('{:25s} {:30s} {:5d} '.format(members[2],"England",30))
print("__________________________________________________________________")

And this will print

__________________________________________________________________
Name                      Country                          Age
__________________________________________________________________
Niroshan                  Srilanka                          20
Brayan                    Australia                         25
Kate                      England                           30
__________________________________________________________________
tripleee
  • 175,061
  • 34
  • 275
  • 318
Niroshan Ratnayake
  • 3,433
  • 3
  • 20
  • 18
8
>>> print(f"{'123':<4}56789")
123 56789
Miladiouss
  • 4,270
  • 1
  • 27
  • 34
6

I found ljust() and rjust() very useful to print a string at a fixed width or fill out a Python string with spaces.

An example

print('123.00'.rjust(9))
print('123456.89'.rjust(9))

# expected output  
   123.00
123456.89

For your case, you case use fstring to print

for prefix in unique:
    if prefix != "":
        print(f"value  {prefix.ljust(3)} - num of occurrences = {string.count(str(prefix))}")

Expected Output

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

You can change 3 to the highest length of your permutation string.

Abu Shoeb
  • 4,747
  • 2
  • 40
  • 45
0

With f string works as well as with format:

https://scientificallysound.org/2016/10/17/python-print3/

f'{some_varaible:<20s}{some_varaible:_<20s}{some_varaible:.<20s}'

Vatslau
  • 11
  • 2