string – How to pad with n characters in Python

string – How to pad with n characters in Python

With Python2.6 or better, theres 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

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 xes

In Python3.6:

>>> 111.ljust(5, x)
111xx

>>> 111.rjust(5, x)
xx111

string – How to pad with n characters in Python

It looks like youre only looking for pointers, not a complete solution. So heres one:

You can multiply strings in python:

>>> A * 4
AAAA

Additionally I would use better names, instead of s Id use text, which is much clearer. Even if your current professor (I suppose youre learning Python in university.) uses such horrible abbreviations.

Leave a Reply

Your email address will not be published. Required fields are marked *