While I was working on one of my many hobby Python projects (I was attempting to scrape novels from some of my favourite online novel sites to convert them to epubs so I can read them offline when I go camping), I noticed that I was doing a lot of this:
There was a lot of copy and pasting going on for all of the | |--
for the print
statements. I got about 6 levels deep and finally decided that enough was enough. I was going to simplify this process because frankly, my print
statements were getting ridiculously long.
A quick search in my code snippets resulted in:
def cprint(text, level: int):
start = '| '
end = '|-- '
print(f"""{start * (level - 1)}{end}{text}""")
The key is the last line which makes use of Python string repetition operator.
print(f"""{start * (level - 1)}{end}{text}""")
Some of you may be wondering why I’m using f-string in the print
statement instead of having the following?
def cprint(text, level: int):
start = '| '
end = '|-- '
print(start * (level - 1), end, text)
The reason for that is because when you have multiple items in a print statement that are comma-separated, python will add an extra space after each item, regardless of whether that item has a value or not. So if I was to call cprint('Some Text', 0)
or cprint('Some Text', 1)
the first option will print
|-- Some Text
whereas the second option will print (there is an extra space at the beginning if you can’t tell)
|-- Some Text
Here they are next to each other for comparison
|-- Some Text
|-- Some Text
Once I updated all my print
statements, my code output now looks like this
That’s it! A simple and quick function to help prettify/simplify your print
statements for better comments readability.