How to underline text using print and format

Viewed 1767

I have a pretty basic python formatting question. I am trying to get all the strings in the following code to be underlined. I have the following code.

print("\u0332{:<20} {:^5} {:>6} {:>10} {:>10}\u0332".format("Name", "Hours Worked", "Hourly Rate", "Taxes Owed", "Net Pay"))

It puts out this:

_Name                 Hours Worked Hourly Rate Taxes Owed    Net Pay̲

How do I get it so all are underlined?

3 Answers

Try this.

print("\u0332".join('{:<20} {:^5} {:>6} {:>10} {:>10}'.format("Name", "Hours Worked", "Hourly Rate", "Taxes Owed", "Net Pay")))

Edit: For each word, a simple list comprehension should do.

words = ["Name", "Hours Worked", "Hourly Rate", "Taxes Owed", "Net Pay"]
words = ["\u0332".join(word+' ')[:-1] for word in words]
print('{:<20} {:^5} {:>6} {:>10} {:>10}'.format(*words))

Using \u0332, I would define a function

from itertools import repeat, chain


def underline(s):
    return ''.join(chain.from_iterable(zip(s, repeat("\u0332"))))

Then write

heads = ["Name", "Hours Worked", "Hourly Rate", "Taxes Owed", "Net Pay"]
print("{:<20} {:^5} {:>6} {:>10} {:>10}".format(*map(underline, heads)))

underline turns a string like "Name" into the string "N\u0332a\u0332m\u0332e\u0332", that is, it adds the combining underline character after each character of the string to underline.


If your terminal supports ANSI escape codes, consider something like

def underline(s):
  return f'\x1b[4m{s}\x1b[24m'

instead. This simply enables your terminal's underline mode while the given string is printed, rather than requiring font support for Unicode glyph composition.

def undaline(strng):
    undlined = ''
    for char in strng:
        undlined += char + "\u0332"
    return undlined

words = ["Name", "Hours Worked", "Hourly Rate", "Taxes Owed", "Net Pay"]
for index, word in enumerate(words):  # creates list of each word in the list underlined
    words[index] = undaline(word)
Related