4
votes

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 :)

3
What you have isn't that verbose to me, especially if you store the string, e.g. s = "This is an underlined headline."; print('{}\n{}'.format(s, len(s)*'-')) - Chris_Rands
As @Chris_Rands mentioned, it is not that verbose. You can call print two times to make it more readable, but that would require variable storing, which is also not that big of a deal - Rodolfo Donã Hosp
Yes, but creating a new variable just for 1 print? What if i have 5 sections, so i need 5 new variables? I hope there is something better. - Max16hr
@Max16hr If you want to do the same thing 5 times, write a function. - khelwood
if you don't want to create additional names use print((lambda s: '%s\n%s' % (s, '-' * len(s)))("This is an underlined headline.")) - panda-34

3 Answers

4
votes

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

0
votes

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.

0
votes

if you want to add an underline to the character we can use this.

print("\u0332".join("This is underline Text "))
text = "This is underline Text"
print("\u0332".join(text))
text = "This is underline Text "
print("\u0332".join(text))
  

Output

T̲h̲i̲s̲ ̲i̲s̲ ̲u̲n̲d̲e̲r̲l̲i̲n̲e̲ ̲T̲e̲x̲t̲ 
T̲h̲i̲s̲ ̲i̲s̲ ̲u̲n̲d̲e̲r̲l̲i̲n̲e̲ ̲T̲e̲x̲t
T̲h̲i̲s̲ ̲i̲s̲ ̲u̲n̲d̲e̲r̲l̲i̲n̲e̲ ̲T̲e̲x̲t̲