python: easiest way to get a string of spaces of length N
What's the easiest way to generat开发者_JAVA技巧e a string of spaces of length N in Python?
(besides something like this, which is multiline and presumably inefficient for large n:
def spaces(n):
s = ''
for i in range(n):
s += ' '
return s
)
try this, simple, only one line:
' ' * n
It's as simple as:
s = ' ' * N
You could do it as a function:
def spaces(n):
return ' ' * n
Or just use the expression:
' ' * n
Off the top of my head:
spaces = lambda x: ' ' * x
All these point mongers are no fun, and their simple answers stink.
The true answer is as follows:
def give_me_spaces(n):
return (lambda : ''.join(' ' for _ in xrange(n)))()
Also it's clearly superior because it uses functional programming.
Had to dig through my python helper functions to find this, but here it is. It's served me well.
spaces = (lambda n:
(lambda z: z(lambda f: lambda m:'' if m <= 0 else ' ' + f(m - 1))(n))
(lambda f:(lambda x:f(lambda*a:x(x)(*a)))(lambda x:f(lambda*a:x(x)(*a)))))
精彩评论