Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad with n characters in Python

Tags:

python

string

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".

like image 429
Gusto Avatar asked Oct 24 '10 14:10

Gusto


People also ask

How do I pad a character in a string in Python?

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.

How do you add N spaces in Python?

To add space in python between two lines or paragraphs we can use the new line character i.e “\n”.

What is \N in Python string?

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.

What does %% mean in Python?

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.


2 Answers

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' 
like image 124
unutbu Avatar answered Oct 08 '22 04:10

unutbu


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 
like image 35
Aditya Advani Avatar answered Oct 08 '22 04:10

Aditya Advani