Skip to content
Advertisement

How to print a string at a fixed width?

I have this code (printing the occurrence of the all permutations in a string)

JavaScript

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:

JavaScript

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

Advertisement

Answer

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:

JavaScript

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:

JavaScript

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:

JavaScript

and you could get the number of occurrences by using combinations in conjunction with count().

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement