snippetpythonCriticalCanonical
How can I fill out a Python string with spaces?
Viewed 0 times
fillwithhowspacescanoutstringpython
Problem
I want to fill out a string with spaces. I know that the following works for zero's:
But what should I do when I want this?:
of course I can measure string length and do
>>> 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.Solution
You can do this with
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
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 'Code Snippets
>>> 'hi'.ljust(10)
'hi 'Context
Stack Overflow Q#5676646, score: 1040
Revisions (0)
No revisions yet.