I should define a function pad_with_n_chars(s, n, c)
that takes a string 's', an integer 'n', and a character 'c' and returns a string consisting of 's' padded with 'c' to create a string with a centered 's' of length 'n'. For example, pad_with_n_chars(”dog”, 5, ”x”)
should return the string "xdogx
".
The standard way to add padding to a string in Python is using the str. rjust() function. It takes the width and padding to be used. If no padding is specified, the default padding of ASCII space is used.
To add space in python between two lines or paragraphs we can use the new line character i.e “\n”.
Newline character in Python: In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.
The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem.
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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With