Python 2.7 格式字符串填充多于一个字符

Python 2.7 format string padding with more than one char

问题

我已经能够用星号填充字符串,但是我想看看是否可以用星号和 space.

填充它

示例输出

我得到了什么

****************************Hello World***************************

...正在尝试

* * * * * * * * * * * * * * Hello World* * * * * * * * * * * * * *

尝试次数

我天真地尝试将 " *" 传递给格式规范的填充参数。返回错误:

Traceback (most recent call last): File "main.py", line 17, in <module> ret_string = '*{:{f}^{n}}'.format(string, f=filler, n=line_len) ValueError: Invalid conversion specification

然后我尝试使用转义字符 "\s*",结果相同。最后我重新访问了文档 6.1.3.1. Format Specification Mini-Language 并看到输入规范似乎仅限于一个字符而不是对字符串开放。有没有解决的办法?我想做一种复合参考,即 {{char1}{char2}} 但这似乎也没有用。

想法?

代码

import fileinput

string     = "Hello World"
ret_string = ""
line_len   = 65
filler    = " *"


for inputstring in fileinput.input():
    string = inputstring.strip(" \n")

ret_string = '{:{f}^{n}}'.format(string, f=filler, n=line_len)
print(ret_string)

你可以用这个小函数做你想做的事,但我不认为你可以用 str.format:

def multi_char_pad(s, f, n):
    to_pad = n - len(s)
    pre = to_pad // 2
    post = to_pad - pre
    f_len = len(f)
    pre_s = f * (pre // f_len) + f[:pre % f_len]
    post_s = f * (post // f_len) + f[:post % f_len]
    return pre_s + s + post_s

你大概一行就可以了,但我觉得这样更容易理解。

padding = "".join(["* "]*10)
print(padding + "hello " + padding)

以下适用于两个字符填充模式:

string = "Hello World"
length = 65
fill = "* "

output = string.center(length, '\x01').replace('\x01\x01', fill).replace('\x01', fill[0])
print(len(output), output)

Python 有一个 center() 函数,它将用单个字符填充字符填充字符串。然后你可以用你的填充图案替换 2 的运行。这可能导致单个字符,因此第二个替换用于这种可能性。 它使用字符 \x01 作为不太可能出现在 string.

中的字符

打印output的长度以证明它是正确的长度。

65 * * * * * * * * * * * * * *Hello World* * * * * * * * * * * * * *