Python: String formatter to get underlined headline
Solution 1
Maybe try using ANSI escape sequences
class Format:
end = '\033[0m'
underline = '\033[4m'
print(Format.underline + 'Your text here' + Format.end)
It will print out underlined text, for the whole ANSI escape sequence documentation click here
Solution 2
There is a unicode character '\u0332'
, COMBINING LOW LINE*, which acts as an underline on the character that precedes it in a string. So you could try:
print('{:s}'.format('\u0332'.join('This is an underlined headline.')))
Which should produce an underlined string:
T̲h̲i̲s̲ ̲i̲s̲ ̲a̲n̲ ̲u̲n̲d̲e̲r̲l̲i̲n̲e̲d̲ ̲h̲e̲a̲d̲l̲i̲n̲e̲.
However the appearance of the output may depend on the application that renders the output, and the fonts it uses. My browser produces an underlined string, my (Linux) terminal displays it as if each character is followed by an underscore.
* There is also '\u0333'
, COMBINING DOUBLE LOW LINE, for double-underlining.
Max16hr
Student of mathematics and trainee in a software company.
Updated on June 04, 2022Comments
-
Max16hr almost 2 years
To structure my console output, I want to print some information and I would like to start with an underlined headline. But how to do it nicely without creating an extra variable?
Right now I do it like this:
print("{:s}\n{:s}\n".format("This is an underlined headline.", len("This is an underlined headline.") * "-"))
what gives me the desired output:
This is an underlined headline. -------------------------------
But that code is bad. Is there some better format string to achieve that?
print("{0:s}\n?????\n".format("This is an underlined headline.", "-"))
Thank you :)
-
Max16hr about 5 yearsI allready tried this but it gives me just
[0mThis is an underlined headline.[4m
-
BoarGules about 5 years@Max16hr That is because your terminal/console doesn't understand ANSI escape sequences. Most versions of Windows between Vista and very recent Windows 10 updates don't.
-
Max16hr about 5 yearsMaybe it is because I'm using Eclipse. So maybe there is some setting to make the console to understand ANSI.
-
Aeossa about 5 yearsI've never really used Eclipse. But this might help
-
Max16hr about 5 yearsNo, also did not work. Now, the ANSI strings seem to be interpreted, I get back my normal string
This is an underlined headline.
But it is still not underlined^^ -
Max16hr about 5 yearsAh! In the preferences I have to disable "Use Windows color mapping". Now it is working! :)
-
Max16hr about 5 yearsYou can also use the
ansi
module (link) instead of writing an own class:from ansi.colour.fx import underline, reset
. -
Gary Vernon Grubb over 3 yearsThis will help make it work in windows: stackoverflow.com/questions/12492810/…
-
snakecharmerb almost 3 yearsTrying this again today, the terminal no longer displays the underscores at all. I'm not sure if this is a font issue or whether I was using a different computer when I wrote the answer originally.