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.
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.
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.
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.
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 '
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!'
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