Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad list in Python

How can I pad a list when printed in python?

For example, I have the following list:

mylist = ['foo', 'bar']

I want to print this padded to four indices, with commas. I know I can do the following to get it as a comma and space separated list:

', '.join(mylist)

But how can I pad it to four indices with 'x's, so the output is like:

foo, bar, x, x
like image 901
Matthieu Cartier Avatar asked Oct 10 '11 14:10

Matthieu Cartier


People also ask

What is PAD in Python?

pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy. pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width.

What is a list () in Python?

List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

How do you pad the end of a string in Python?

You can do this with str. 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) . ljust(), rjust() have been deprecated from the string module only.


1 Answers

In [1]: l = ['foo', 'bar']

In [2]: ', '.join(l + ['x'] * (4 - len(l)))
Out[2]: 'foo, bar, x, x'

The ['x'] * (4 - len(l)) produces a list comprising the correct number of 'x'entries needed for the padding.

edit There's been a question about what happens if len(l) > 4. In this case ['x'] * (4 - len(l)) results in an empty list, as expected.

like image 88
NPE Avatar answered Sep 18 '22 22:09

NPE