Python 2.7格式字符串填充,包含多个char

时间:2018-05-29 18:26:59

标签: python string string-formatting

问题

我已经能够用星号填充一个字符串,但是我想看看是否可以用星号和空格填充它。

示例输出

我能得到什么

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

...试图获得

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

的尝试

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

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)

3 个答案:

答案 0 :(得分:1)

以下内容适用于两种字符填充模式:

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* * * * * * * * * * * * * *

答案 1 :(得分:0)

你可以使用这个小功能来做你想做的事情,但是我不能用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

你可能只有一行,但我认为它更容易理解。

答案 2 :(得分:0)

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