Home > OS >  Formatting spaces in print
Formatting spaces in print

Time:03-06

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.

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

CodePudding user response:

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
  • Related