问题
我已经能够用星号填充字符串,但是我想看看是否可以用星号和空格填充它。
示例输出
我得到了什么
****************************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)
最佳答案
以下适用于两个字符填充模式:
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* * * * * * * * * * * * * *
关于具有多个字符的 Python 2.7 格式字符串填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50590720/