Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fill out a Python string with spaces?

I want to fill out a string with spaces. I know that the following works for zero's:

>>> print  "'%06d'"%4 '000004' 

But what should I do when I want this?:

'hi    ' 

of course I can measure string length and do str+" "*leftover, but I'd like the shortest way.

like image 583
taper Avatar asked Apr 15 '11 12:04

taper


People also ask

Can strings have spaces in Python?

Per W3 schools: A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.

How do you add a space padding 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 fix 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.


2 Answers

You can do this with str.ljust(width[, fillchar]):

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

>>> 'hi'.ljust(10) 'hi        ' 
like image 110
Felix Kling Avatar answered Oct 04 '22 13:10

Felix Kling


For a flexible method that works even when formatting complicated string, you probably should use the string-formatting mini-language,

using either f-strings

>>> f'{"Hi": <16} StackOverflow!'  # Python >= 3.6 'Hi               StackOverflow!' 

or the str.format() method

>>> '{0: <16} StackOverflow!'.format('Hi')  # Python >=2.6 'Hi               StackOverflow!' 
like image 28
simon Avatar answered Oct 04 '22 11:10

simon