How can I fill out a Python string with spaces?
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) .
Its gone in python 3? Just wanted to add there is also rjust and center which work much the same way but for different alignments
ljust(), rjust() have been deprecated from the string module only. They are available on the str builtin type.
For a flexible method that works even when formatting complicated string, you probably should use the string-formatting mini-language,
>>> f' StackOverflow!' # Python >= 3.6 'Hi StackOverflow!'
>>> ' StackOverflow!'.format('Hi') # Python >=2.6 'Hi StackOverflow!'
I had problems with this type of formatting when I was using national accents. You would want ‘kra’ and ‘krá’ to be the same, but they were not.
Don’t use str.format() for templates with only a single <. >and nothing else. Just use the format() function and save yourself the parsing overhead: format(‘Hi’, ‘<16') .
The string format method lets you do some fun stuff with nested keyword arguments. The simplest case:
If you want to pass in 16 as a variable:
>>> '>'.format(message='Hi', width=16) 'Hi '
If you want to pass in variables for the whole kit and kaboodle:
'>'.format( message='Hi', fill=' ', align='
Which results in (you guessed it):
And for all these, you can use python 3.6+ f-strings:
message = 'Hi' fill = ' ' align = '>'
I like this common printf syntax much better. Allows you to write complex strings without countless concatenations.
Correct way of doing this would be to use Python's format syntax as described in the official documentation
For this case it would simply be:
''.format('hi')
which outputs:
'hi '
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] fill ::= align ::= "" | "=" | "^" sign ::= "+" | "-" | " " width ::= integer precision ::= integer type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Pretty much all you need to know is there ^.
Update: as of python 3.6 it's even more convenient with literal string interpolation!
foo = 'foobar' print(f' is great!') # foobar is great!
You should also consider string.zfill() , str.rjust() and str.center() for string formatting. These can be chained and have the 'fill' character specified, thus:
>>> ('3'.zfill(8) + 'blind'.rjust(8) + 'mice'.ljust(8, '.')).center(40) ' 00000003 blindmice. '
These string formatting operations have the advantage of working in Python v2 and v3.
Take a look at pydoc str sometime: there's a wealth of good stuff in there.
Thanks for pointing out the str.center(n) method. It was just what i was looking for and didn't even know its existance. 😀
As of Python 3.6 you can just do
Or, if your padding size is in a variable, like this (thanks @Matt M.!):
f'
TL;DR
Longer explanation
Since Python3.6 you can use f-strings literal interpolation.
Variable space:
value = 4 space = 10 # move value to left print(f'foo > bar') # foo 4 bar # move value to right print(f'foo > bar') # foo 4 bar # center value print(f'foo bar') # foo 4 bar
Constant space:
value = 4 # move value to left print(f'foo bar') # foo 4 bar # move value to right print(f'foo 10> bar') # foo 4 bar # center value print(f'foo bar') # foo 4 bar
If you want to padd with some other char then space, specify it at the beginning:
value = 4 space = 10 padd = '_' print(f'foo ^> bar') # foo ____4_____ bar print(f'foo bar') # foo ____4_____ bar
Add a space in string
Ignacio, can you please be more welcoming and useful, especially for an OP with 21 rep, so, obviously pretty new? Explain what you mean. e.g. Well, it looks like you already have a space to the left. I think your output should actually look more like "How many times did namego here". Is that correct?
@leoger: Please consider the vague possibility that you may be unusefully and mistakenly barking up the wrong tree. I think that the OP's print statement prints nothing, because it has a syntax error. Is that correct?
4 Answers 4
print "How many times did " + name + " go here?"
print "How many times did", name, "go here?"
print "How many times did %s go here?" % name
The preferred form in this simple case is the second one. The first uses concatenation (which is useful if you want more or less than one space between parts), the second uses the comma operator, which in the context of print joins the strings with a space, and the third uses string formatting (the old style), which should look familiar if you come from C, Perl, PHP, etc. The third is the most powerful form, but in this simple cases the use of format strings is unnecessary.
Note that in Python, lines do not need to be (and should not be) ended by semicolons. You can also use some of the string justification methods to add several spaces on either or both sides of the string.
Efficient way to add spaces between characters in a string
Say I have a string s = 'BINGO' ; I want to iterate over the string to produce 'B I N G O' . This is what I did:
result = '' for ch in s: result = result + ch + ' ' print(result[:-1]) # to rid of space after O
On my machine, this takes about 500ns. Is that really a bottleneck in your program? If not, don't ask about efficiency; ask about simplicity, readability, etc.—things that actually matter.
@abarnert perhaps efficient means something particular to you, but it doesn't actually necessarily mean machine efficiency.
@kojiro: "efficient" means something particular in the disciple/profession/hobby/etc. of computer programming, which is what this site is about, so that's the definition that matters. That's why this site has an efficiency tag that's intended and used for exactly that purpose.
Yes, @abarnert's right -- the problem with this solution isn't first of all that it's inefficient, it's that it's not Pythonic and not simple. ' '.join(s) is the simple, Pythonic way. However, efficiency is a concern, as the above solution will be O(N^2) , whereas the join is O(N) -- this won't matter for 'BINGO' but will matter for long strings.
@BenHoyt: The reason it looks linear with smallish strings is that copying a string is basically just a call to memmove—which still loops, of course, but it does so in C code that's usually highly optimized for the platform (especially on x86, which has opcodes specifically designed to speed up memmove). So, the constant multiplier on the second N is orders of magnitude smaller than the one on the first, which makes it hard to see until N gets very large.