Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How can I pad a string with spaces from the right and left?

Tags:

python

string

I have two scenarios where I need to pad a string with whitespaces up to a certain length, in both the left and right directions (in separate cases). For instance, I have the string:

TEST 

but I need to make the string variable

_____TEST1 

so that the actual string variable is 10 characters in length (led by 5 spaces in this case). NOTE: I am showing underscores to represent whitespace (the markdown doesn't look right on SO otherwise).

I also need to figure out how to reverse it and pad whitespace from the other direction:

TEST2_____ 

Are there any string helper functions to do this? Or would I need to create a character array to manage it?

Also note, that I am trying to keep the string length a variable (I used a length of 10 in the examples above, but I'll need to be able to change this).

Any help would be awesome. If there are any python functions to manage this, I'd rather avoid having to write something from the ground up.

Thanks!

like image 433
Brett Avatar asked Feb 08 '13 16:02

Brett


People also ask

How do you put a space in a string in Python?

We add space in string in python by using rjust(), ljust(), center() method. To add space between variables in python we can use print() and list the variables separate them by using a comma or by using the format() function.

How do you control spaces in Python?

strip(): The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.

How do you do right padding in Python?

Python String rjust() Method Python string method rjust() returns the string right 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).


2 Answers

You can look into str.ljust and str.rjust I believe.

The alternative is probably to use the format method:

>>> '{:<30}'.format('left aligned') 'left aligned                  ' >>> '{:>30}'.format('right aligned') '                 right aligned' >>> '{:^30}'.format('centered') '           centered           ' >>> '{:*^30}'.format('centered')  # use '*' as a fill char '***********centered***********' 
like image 134
mgilson Avatar answered Sep 21 '22 08:09

mgilson


Python3 f string usage

l = "left aligned" print(f"{l.ljust(30)}")  r = "right aligned" print(f"{r.rjust(30)}")  c = "center aligned" print(f"{c.center(30)}") 

>>> l = "left aligned" >>> print(f"{l.ljust(30)}") left aligned                    >>> r = "right aligned" >>> print(f"{r.rjust(30)}")                  right aligned  >>> print(f"{c.center(30)}")         center aligned         
like image 26
Ashton Honnecke Avatar answered Sep 19 '22 08:09

Ashton Honnecke