From How can I fill out a Python string with spaces?, the accepted answer to pad character to string on the right is to use the str.ljust()
.
But if we want to pad character to string on the left, we can use str.rjust()
and to pad on both we can use str.center()
, e.g.
>>> s = 'foobar'
>>> s.ljust(len(s)+1) # pads one space to the right
'foobar '
>>> s.rjust(len(s)+1) # pads one space to the left
' foobar'
>>> s.center(len(s)+2) # pads one space to both left and right
' foobar '
But on the backend, is that really more efficient than simply doing this?:
>>> ' ' + s + ' '
' foobar '
>>> ' '*10 + s + ' '*10 # pads ten spaces to both left and right
' foobar '
Is the str.center()
/str.ljust()
/str.rjust()
more readable than the ' ' + s + ' '
?
The str
functions and the ' ' + s + ' '
doing the different thing at the assembly level as shown in:
>>> import dis
>>> dis.dis(lambda: ' ' + s + ' ')
1 0 LOAD_CONST 1 (' ')
3 LOAD_GLOBAL 0 (s)
6 BINARY_ADD
7 LOAD_CONST 1 (' ')
10 BINARY_ADD
11 RETURN_VALUE
>>> dis.dis(lambda: s.center(len(s)+2))
1 0 LOAD_GLOBAL 0 (s)
3 LOAD_ATTR 1 (center)
6 LOAD_GLOBAL 2 (len)
9 LOAD_GLOBAL 0 (s)
12 CALL_FUNCTION 1
15 LOAD_CONST 1 (2)
18 BINARY_ADD
19 CALL_FUNCTION 1
22 RETURN_VALUE
Are there any other methods to do the same thing which is/are more pythonic / efficient?
EDITED
Alternatively, this seems to save one step in the disassembler:
>>> ' {} '.format(s)
' foobar '
>>> dis.dis(lambda: ' {} '.format(s))
1 0 LOAD_CONST 1 (' {} ')
3 LOAD_ATTR 0 (format)
6 LOAD_GLOBAL 1 (s)
9 CALL_FUNCTION 1
12 RETURN_VALUE
So is the saving in the disassembler an improvement in efficiency? Or is it no different from the ' ' + s + ' '
?