如何在 Python 中使文本加粗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24834876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:18:49  来源:igfitidea点击:

How can I make text bold in Python?

pythontextinputformat

提问by user2921139

I want to be able to change the text to bold in Python. Is there a way to do that?

我希望能够在 Python 中将文本更改为粗体。有没有办法做到这一点?

I have been able to change colors with termcolor but nothing so far with bold text. Has anyone tried doing it before?

我已经能够使用 termcolor 更改颜色,但到目前为止还没有使用粗体文本。有没有人试过这样做?

采纳答案by CrossSquare

You might want to try ANSI escape sequences ifyour platform allows it.

如果您的平台允许,您可能想尝试 ANSI 转义序列。

Crossposting from related - and possible duplicate - SO questions: 12

从相关的交叉发布 - 和可能的重复 - SO 问题:1 2

Before you proceed, please read the warnings in the above links to make sure your operating system and Python version will allow you to properly render this.

在继续之前,请阅读上述链接中的警告,以确保您的操作系统和 Python 版本允许您正确呈现此内容。

You can define a class containing all of the ANSI escape sequences you need.

您可以定义一个包含您需要的所有 ANSI 转义序列的类。

class style:
   BOLD = '3[1m'
   END = '3[0m'

Then printthem via concatenated class calls:

然后print它们通过连接的类调用:

print style.BOLD + 'This is my text string.' + style.END

If you don't want to go through the hassle of creating an entire class just to get bold text, you can obviously concatenate them directly instead. However, if your code is open-source and not for personal use, make sure you tell other potential readers what this does!

如果您不想为了获得粗体文本而经历创建整个类的麻烦,您显然可以直接将它们连接起来。但是,如果您的代码是开源的且不供个人使用,请确保您告诉其他潜在读者这是做什么的!

print '3[1m' + 'This is my text string.' + '3[0m'

Does this answer your question?

这回答了你的问题了吗?

Edit: JYelton beat me to it. I'm such a slow typer...

编辑:JYelton 击败了我。我打字很慢...