具有多个字符的 Python 2.7 格式字符串填充

标签 python string string-formatting

问题

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

示例输出

我得到了什么

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

相关文章:

python - 当切片索引超出范围时如何引发 IndexError?

python - jinja 2 嵌套字典到 yaml

带有单引号查找的 Java 正则表达式错误?

java - 在哪里可以找到有关 Java SimpleFormatter 格式字符串的文档?

PHP:如何通过 sprintf() 添加前导零/零填充以 float ?

python - Django makemigrations 有效,迁移失败,显示 "django.db.utils.IntegrityError: NOT NULL constraint failed"

python - 如何从 Python 控制 Windows 应用程序

vb.net - String.Contains(Array?..) - VB.NET 中的坏词过滤器

c++ - C/C++ 将二进制数据映射到结构成员

c - 强制 fscanf 消耗可能的空白