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.

Answer from 0x90 on Stack Overflow
Top answer
1 of 8
320

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.

2 of 8
145

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().

🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › hardware and peripherals › raspberry pi pico › micropython
f string for fixed width output - Raspberry Pi Forums
June 10, 2023 - Just for the record, I tried str(100)[:8] but it doesn't fill up to the full 8 character width: print(str(100)[:8]) 100 I'll just use one of the two slightly untidy solutions I know work (see OP) as there doesn't seem to be a better way. Thank you all for taking the time to make suggestions. ... Here's half a solution: an eng(n) function that returns to numbers: n scaled to be < 1000 and the power of ten, rounded to threes. I'm sure you can do something with f-strings to make the output you want from this: ... #!/usr/bin/env python3 # -*- coding: utf-8 -*- # for https://forums.raspberrypi.com/viewtopic.php?t=352436 def eng(n): # returns two values: # 1.) number normalized to be (abs) less than 1000 # 2.) power of 10, rounded to threes # inspired by Jukka Korpela's https://jkorpela.fi/c/eng.html # scruss, 2023-06.
🌐
DEV Community
dev.to › erictleung › print-fixed-fields-using-f-strings-in-python-26ng
Print fixed fields using f-strings in Python - DEV Community
August 20, 2020 - To do so, you can use the syntax used in other Python formatting. init = 34 end = 253 print(f"You had this much money : ${init:5}") print(f"Now you have this much money : ${end:5}") # You had this much money : $ 34 # Now you have this much money : $ 253 # Spacing width 12345
🌐
YouTube
youtube.com › pygpt
python f string fixed width - YouTube
Download this code from https://codegive.com Python's f-strings provide a concise and convenient way to format strings. One useful feature of f-strings is th...
Published   December 23, 2023
Views   1
🌐
Python.org
discuss.python.org › python help
How to use f string format without changing content of string? - Python Help - Discussions on Python.org
June 15, 2022 - def engine(current_money=10.0): # Instruction print( f""" --------------------------------------------------------------------------- | You start with ${current_money} …
🌐
Bobby Hadz
bobbyhadz.com › blog › python-format-number-fixed-width
Format a Number to a fixed Width in Python | bobbyhadz
Use a formatted string literal to format a number to a fixed width, e.g. `result = f'{my_int:03d}'`.
🌐
ZetCode
zetcode.com › python › fstring
Python f-string - formatting strings in Python with f-string
May 11, 2025 - F-strings allow you to dynamically set the width and precision of your formatted output by using variables instead of hardcoded values. This provides great flexibility when you need to adjust formatting based on runtime conditions or user preferences. ... #!/usr/bin/python value = 123.456789 ...
🌐
Python Forum
python-forum.io › thread-18651.html
fixed width numbers
is there an easy way to output numbers in a simple print() call in a fixed width? for cases with leading zeros i have been doing:print(str(number+1000000))but now i want to have leading spaces. do i n
Find elsewhere
🌐
Python Morsels
pythonmorsels.com › string-formatting
Python f-string tips & cheat sheets - Python Morsels
April 12, 2022 - Space-padding can be helpful if ... in a fixed-width setting (in a command-line program for example). If you prefer, you can add a space before the Nd specifier (so it'll look more like its sibling, the 0Nd modifier): ... If you'd like to space-pad floating point numbers, check out >N in the section on strings ...
🌐
Real Python
realpython.com › how-to-python-f-string-format-float
How to Format Floats Within F-Strings in Python – Real Python
April 24, 2024 - Now, it’s time to move on and ... within strings. ... In addition to their precision, format specifiers contain a width parameter. This allows you to set the total number of characters used to display the number. If your number’s length exceeds the width parameter, then additional space is assigned. Otherwise, the result will be left-padded with spaces to its specified width. Assuming you set your width to fit the largest number, each number will have the same fixed length as ...
🌐
Bentley
cissandbox.bentley.edu › sandbox › wp-content › uploads › 2022-02-10-Documentation-on-f-strings-Updated.pdf pdf
A Guide to Formatting with f-strings in Python - CIS Sandbox
shows how you can use f-strings to display the value of a variable in the form: variable ... What You Get (WYSIWYG). The procedure is as follows: • Placing between the quotation marks after the 'f' the text that you want displayed · • Enclosing the variables to be displayed within the text in curly braces · • Within those curly braces, placing a colon (:) after the variable · • Formatting the variable using a format specification (width, alignment, data type) after
🌐
GeeksforGeeks
geeksforgeeks.org › python › format-a-number-width-in-python
Format a Number Width in Python - GeeksforGeeks
July 23, 2025 - In this article, we'll explore various methods and techniques in Python to format numbers to a fixed width. This code demonstrates how to use f-strings in Python to format integers to fixed widths, with options to pad them with leading zeros or spaces, depending on the desired output format.
🌐
TutorialsPoint
tutorialspoint.com › How-to-format-a-floating-number-to-fixed-width-in-Python
How to format a floating number to fixed width in Python?
November 13, 2024 - f-strings: Convenient way to set ... number to a fixed width by using Python's f-strings, in below code '.2f' specifies that the number should formatted as a floating-point number with 2 decimal places....
🌐
Python
docs.python.org › 3 › library › string.html
Common string operations — Python 3.14.3 documentation
Changed in version 3.10: Preceding the width field by '0' no longer affects the default alignment for strings.
🌐
Medium
medium.com › @NirantK › best-of-python3-6-f-strings-41f9154983e
Best of Python3.6 f-strings. f-strings (formatted strings) for those… | by Nirant Kasliwal | Medium
April 16, 2018 - This is much easier with Python f-strings using the colon ‘:’ operator, followed by a an alignment operator and field width value.
🌐
Saralgyaan
saralgyaan.com › posts › f-string-in-python-usage-guide
Python f-strings - The Ultimate Usage Guide
July 23, 2025 - ladbrokes立博-公司官网 版权所有 地址:ladbrokes立博 邮编:250100 电话:0534-8985830
🌐
Real Python
realpython.com › python-f-strings
Python's F-String for String Interpolation and Formatting – Real Python
November 30, 2024 - Python's f-strings provide a readable way to interpolate and format strings. They're readable, concise, and less prone to error than traditional string interpolation and formatting tools, such as the .format() method and the modulo operator (%). F-strings are also faster than those tools!