Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Formatting spaces in print

I am trying to create a new print function in such a way that it prints colored text.
"\033[1;31m" make the cursor print in red and "\033[0;0m" reverts it back.

The color changing works perfectly but built-in print function is printing a space between every instance. How this space can be avoided?

I know about sep and end but using sep='' will change the behaviour of the whole print function. I only want no gap between the leftmost letter and margin.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from builtins import print as b_print

def print(*args, **kwargs):
    b_print("\033[1;31m", *args, "\033[0;0m", **kwargs)

Output

print("Hello world")
>>><Space><red>Hello world</red>

Required

>>><red>Hello world</red>

What doesn’t work

b_print("\033[1;31m", '\r', *args, "\033[0;0m", **kwargs)
# as there will be one more tab after \r

b_print("\033[1;31m", *args, "\033[0;0m", **kwargs, sep='')
# as it enforces seperator to be '' between all the args.
from builtins import print as p

b_print("\033[1;31m", '\b', *args,"\033[0;0m", **kwargs)
# as creating a new argument create a new space character

>Solution :

You have to do a bit more of the work manually: Take a sep parameter, convert *args to str, and join on sep.

from builtins import print as b_print

def print(*args, sep=' ', **kwargs):
    b_print("\033[1;31m" + sep.join(map(str, args)) + "\033[m", **kwargs)

print("Hello", "world", 7, sep='-')

Demo:

print("Hello", "world", 7, sep='-', end='x')

Output is like:

<red>Hello-world-7</red>x
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading