如何用空格填充Python字符串?

问题:如何用空格填充Python字符串?

我想用空格填充字符串。我知道以下内容适用于零:

>>> print  "'%06d'"%4
'000004'

但是,当我想要这个怎么办?:

'hi    '

当然,我可以测量字符串长度并这样做str+" "*leftover,但我想用最短的方法。

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.


回答 0

您可以使用str.ljust(width[, fillchar])

返回长度为width的左对齐字符串。使用指定的fillchar(默认为空格)填充。如果width小于,则返回原始字符串len(s)

>>> 'hi'.ljust(10)
'hi        '

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        '

回答 1

为了即使在格式化复杂的字符串时也可以使用灵活的方法,您可能应该使用string-formatting mini-language,无论使用哪种str.format()方法

>>> '{0: <16} StackOverflow!'.format('Hi')  # Python >=2.6
'Hi               StackOverflow!'

F-串

>>> f'{"Hi": <16} StackOverflow!'  # Python >= 3.6
'Hi               StackOverflow!'

For a flexible method that works even when formatting complicated string, you probably should use the string-formatting mini-language, using either the str.format() method

>>> '{0: <16} StackOverflow!'.format('Hi')  # Python >=2.6
'Hi               StackOverflow!'

of f-strings

>>> f'{"Hi": <16} StackOverflow!'  # Python >= 3.6
'Hi               StackOverflow!'

回答 2

新的(ish)字符串格式方法使您可以使用嵌套关键字参数来做一些有趣的事情。最简单的情况:

>>> '{message: <16}'.format(message='Hi')
'Hi             '

如果要16作为变量传递:

>>> '{message: <{width}}'.format(message='Hi', width=16)
'Hi              '

如果要为整个工具包和kaboodle传递变量,请执行以下操作

'{message:{fill}{align}{width}}'.format(
   message='Hi',
   fill=' ',
   align='<',
   width=16,
)

结果(您猜对了):

'Hi              '

The new(ish) string format method lets you do some fun stuff with nested keyword arguments. The simplest case:

>>> '{message: <16}'.format(message='Hi')
'Hi             '

If you want to pass in 16 as a variable:

>>> '{message: <{width}}'.format(message='Hi', width=16)
'Hi              '

If you want to pass in variables for the whole kit and kaboodle:

'{message:{fill}{align}{width}}'.format(
   message='Hi',
   fill=' ',
   align='<',
   width=16,
)

Which results in (you guessed it):

'Hi              '

回答 3

您可以尝试以下方法:

print "'%-100s'" % 'hi'

You can try this:

print "'%-100s'" % 'hi'

回答 4

正确的方法是使用官方文档中所述的Python格式语法

对于这种情况,它将简单地是:
'{:10}'.format('hi')
哪个输出:
'hi '

说明:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

您几乎需要知道的全部都在那里^。

更新:从python 3.6开始,使用文字字符串插值更加方便!

foo = 'foobar'
print(f'{foo:10} is great!')
# foobar     is great!

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:
'{:10}'.format('hi')
which outputs:
'hi '

Explanation:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
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'{foo:10} is great!')
# foobar     is great!

回答 5

用途str.ljust()

>>> 'Hi'.ljust(6)
'Hi    '

您还应该考虑string.zfill()str.ljust()以及str.center()用于字符串格式化。这些可以链接起来并指定“ fill ”字符,因此:

>>> ('3'.zfill(8) + 'blind'.rjust(8) + 'mice'.ljust(8, '.')).center(40)
'        00000003   blindmice....        '

这些字符串格式化操作的优势在于可以在Python v2和v3中使用。

看一下pydoc str某个时间:里面有很多好东西。

Use str.ljust():

>>> 'Hi'.ljust(6)
'Hi    '

You should also consider string.zfill(), str.ljust() 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.


回答 6

从Python 3.6开始,您可以执行

>>> strng = 'hi'
>>> f'{strng: <10}'

文字字符串插值

或者,如果您的填充大小在变量中,例如这样(感谢@Matt M.!):

>>> to_pad = 10
>>> f'{strng: <{to_pad}}'

As of Python 3.6 you can just do

>>> strng = 'hi'
>>> f'{strng: <10}'

with literal string interpolation.

Or, if your padding size is in a variable, like this (thanks @Matt M.!):

>>> to_pad = 10
>>> f'{strng: <{to_pad}}'

回答 7

您还可以将字符串居中

'{0: ^20}'.format('nice')

you can also center your string:

'{0: ^20}'.format('nice')

回答 8

对字符串使用Python 2.7的迷你格式

'{0: <8}'.format('123')

左对齐,并用”字符填充到8个字符。

Use Python 2.7’s mini formatting for strings:

'{0: <8}'.format('123')

This left aligns, and pads to 8 characters with the ‘ ‘ character.


回答 9

只需删除0,它将增加空间:

>>> print  "'%6d'"%4

Just remove the 0 and it will add space instead:

>>> print  "'%6d'"%4

回答 10

使用切片会不会更pythonic?

例如,要在字符串的右边填充空格,直到其长度为10个字符:

>>> x = "string"    
>>> (x + " " * 10)[:10]   
'string    '

要在其左侧填充空格,直到其长度为15个字符:

>>> (" " * 15 + x)[-15:]
'         string'

当然,它需要知道要填充多长时间,但是并不需要测量开始的字符串的长度。

Wouldn’t it be more pythonic to use slicing?

For example, to pad a string with spaces on the right until it’s 10 characters long:

>>> x = "string"    
>>> (x + " " * 10)[:10]   
'string    '

To pad it with spaces on the left until it’s 15 characters long:

>>> (" " * 15 + x)[-15:]
'         string'

It requires knowing how long you want to pad to, of course, but it doesn’t require measuring the length of the string you’re starting with.


回答 11

一个很好的技巧来代替各种打印格式:

(1)在右边加空格:

('hi' + '        ')[:8]

(2)在左前导零处填充:

('0000' + str(2))[-4:]

A nice trick to use in place of the various print formats:

(1) Pad with spaces to the right:

('hi' + '        ')[:8]

(2) Pad with leading zeros on the left:

('0000' + str(2))[-4:]

回答 12

您可以使用列表理解来做到这一点,这也会使您对空格的数量有所了解,并且只能是一个内衬。

"hello" + " ".join([" " for x in range(1,10)])
output --> 'hello                 '

You could do it using list comprehension, this’d give you an idea about the number of spaces too and would be a one liner.

"hello" + " ".join([" " for x in range(1,10)])
output --> 'hello                 '