如何在Python中打印带有下划线的文本?

11
print("hello")

输出应该是单词 "hello",但要带有下划线。


1
可能是如何在Python中打印粗体文本?的重复问题。 - Timothée Poisot
7个回答

32

你可以通过使用转义字符来实现。

print("\033[4mhello\033[0m")

2
对我来说它不起作用,它只是打印 - [4mhello[0m。 - AlokThakur
根据类似问题的这条评论,@AlokThakur,它可能无法在不理解ANSI转义序列的终端上工作。 - syockit
请参考此答案,使其在Windows中正常工作:https://dev59.com/IWcs5IYBdhLWcg3w5IBa#64222858 - Gary Vernon Grubb

2
这肯定会起作用:

print("\u0332".join("hello "))

1

这个解决方案给我输出了以下内容:h_e_l_l_o - Ahmed Akhtar
是的,它有点奏效。我得到了一个字母双下划线和一个字母没有下划线。 - Taylrl

1

我曾经遇到过这个问题,而且在我的情况下,问题出在了'colorama.init(autoreset=True)'这一行。由于某种原因,在Python3 Windows中,如果使用Colorama自动重置功能,则无法打印带有下划线的文本(您仍然可以打印加粗文本、前景色、背景色等,到目前为止,我发现只有下划线格式受到影响)。当然,这也意味着您需要通过添加ANSI重置序列ESC [0m (在下面的示例中,这将是print语句末尾的\033[0m)来手动重置文本。

import colorama
#colorama.init(autoreset=True) #This line was causing me problems
#import os #To use below line
#os.system("") #This line can make it work in some terminals
print("\033[1;4mBold and underlined text\033[0m")

经过进一步测试,以下是一些附加说明:

  • 在某些终端上可能仍然无法正常工作。例如,我首先在 VSC (Visual Studio Code) 内置终端上尝试了这个方法,它可以正常工作,但是当我在 cmd 上尝试时,它却无法正常工作。
  • 在无法正常工作的终端上,在print语句之前添加os.system("")行可以使其正常工作。我在cmd上进行了测试并且它可以正常工作(colorama.init(autoreset=True)行仍被注释掉)。

编辑:为完整性添加了“import colorama”行和其他说明。


0

请确保您已经安装了Python 3.6+ 使用pip安装quo https://pypi.org/project/quo

from quo import echo
echo(f"Hello World!!!", underline=True) 

0

确保您安装了Python3解释器 然后运行

x="the solution"
print("\033[4m" + x + "\033[0m")

0
string = 'Hello world'
emptystring = ''

for i in range(0, len(string)):

    if string[i] == ' ':
        emptystring = emptystring + string[i]
    else:
        emptystring= emptystring+string[i]+str('\u0332')

print(emptystring)

这里是输出结果


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接