With Python2.6 or better, there's no need to define your own function; the string format method can do all this for you:
In [18]: '{s:{c}^{n}}'.format(s='dog',n=5,c='x')
Out[18]: 'xdogx'
Using f-string: f'{"dog":x^5}'
With Python2.6 or better, there's no need to define your own function; the string format method can do all this for you:
In [18]: '{s:{c}^{n}}'.format(s='dog',n=5,c='x')
Out[18]: 'xdogx'
Using f-string: f'{"dog":x^5}'
yeah just use ljust or rjust to left-justify (pad right) and right-justify (pad left) with any given character.
For example ... to make '111' a 5 digit string padded with 'x'es
In Python3.6:
>>> '111'.ljust(5, 'x')
111xx
>>> '111'.rjust(5, 'x')
xx111
You can use ljust() and rjust() of string objects in python:
customer = 'John Doe'
balance = 39.99
output = customer.ljust(15, '.') + str(balance).rjust(10, '.')
print(output)
#John Doe............39.99
Depending on format you need, you can tune it with changing the widths or adding space characters.
If you did not want to have spaces on either side of the dots as the other answer would suggests, you can achieve that specifying formatting just as well:
"{:.<17s}{:.>8.2f}".format(customer, balance)
Would do 17 characters wide left aligned, . right padded string and 8 characters of right aligned, . left padded, float with precision of 2 decimal points.
You can do that same with an f-string (Python >=3.6):
f"{customer:.<17s}{balance:.>8.2f}"
However, if you also want to include the space on either side of the dots, it gets trickier. You can still do that, but you need to double pad / format or concatenate before filling in the gap:
"{:.<16s}{:.>9s}".format(f"{customer} ", f" {balance:>.2f}")
But I would be somewhat at pain to call that more elegant.
You could also do all that with formatting:
# Fill in with calculated number of "."
"{} {} {:.2f}".format(customer,
"."*(25 - (2 + len(customer) + len(f"{balance:.2f}"))),
balance)
# Similarly used for calculated width to pad with "."
"{} {:.^{}s} {:.2f}".format(customer,
"",
25 - (2 + len(customer) + len(f"{balance:.2f}")),
balance)
But again, more elegant is it really not.
Specify it before the alignment character (> or <), without apostrophes.
contents = {"Introduction": 1, "Python Basics": 5, "Creating Your First Program": 12, "Operators and Variables": 29}
for chapt, page in contents.items():
print(f"{chapt:.<30}{page:.>5}")
Outputs:
Introduction......................1
Python Basics.....................5
Creating Your First Program......12
Operators and Variables..........29
From the documentation
If a valid align value is specified, it can be preceded by a fill character that can be any character and defaults to a space if omitted. It is not possible to use a literal curly brace (โ
{โ or โ}โ) as the fill character in a formatted string literal or when using thestr.format()method. However, it is possible to insert a curly brace with a nested replacement field. This limitation doesnโt affect theformat()function
According to the Format Specification Mini-Language you have to specify it before the "align":
contents = [('Introduction', 1), ('Python Basics', 5),
('Creating Your First Program', 12),
('Operators and Variables', 29)]
row_length = 35
for chapt, page in contents:
dots = str(row_length - len(str(page)))
print(f"{chapt:.<{dots}}{page}")
*This is now independent of the page number's length. A little bit more flexible.
You can do this with str.ljust(width[, fillchar]):
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than
len(s).
>>> 'hi'.ljust(10)
'hi '
For a flexible method that works even when formatting complicated string, you probably should use the string-formatting mini-language,
using either f-strings
>>> f'{"Hi": <16} StackOverflow!' # Python >= 3.6
'Hi StackOverflow!'
or the str.format() method
>>> '{0: <16} StackOverflow!'.format('Hi') # Python >=2.6
'Hi StackOverflow!'
>>> print(' MENU '.center(80, '*'))
************************************* MENU *************************************
Note that 80 is not the actual width of the screen. It's just an arbitrary number I choose because it's the usual size of the console window on Windows. If you want to determine the actual screen width you can try these examples for Linux and Windows.
You can also do this with format strings
In [32]: '{0:*^80}'.format('MENU')
Out[32]: '**************************************MENU**************************************'
This says use the '*' character to pad 'MENU' to 80 characters in the center. The '^' character indicates center.