Python:字符串格式化程序以获得带下划线的标题

Max*_*6hr 4 python printing string format python-3.7

为了构建我的控制台输出,我想打印一些信息,并且我想从带下划线的标题开始。但是如何在不创建额外变量的情况下很好地做到这一点呢?

现在我这样做:

print("{:s}\n{:s}\n".format("This is an underlined headline.", len("This is an underlined headline.") * "-"))
Run Code Online (Sandbox Code Playgroud)

是什么给了我想要的输出:

This is an underlined headline.
-------------------------------
Run Code Online (Sandbox Code Playgroud)

但该代码很糟糕。有没有更好的格式字符串来实现这一点?

print("{0:s}\n?????\n".format("This is an underlined headline.", "-"))
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

小智 6

也许尝试使用ANSI 转义序列

class Format:
    end = '\033[0m'
    underline = '\033[4m'

print(Format.underline + 'Your text here' + Format.end)
Run Code Online (Sandbox Code Playgroud)

它将打印出带下划线的文本,有关整个 ANSI 转义序列文档,请单击此处

  • @Max16hr 那是因为你的终端/控制台不理解 ANSI 转义序列。Vista 和最新的 Windows 10 更新之间的大多数 Windows 版本都没有。 (2认同)