0

I am trying to print the text in various colors to highlight the differences. But I am getting one character of space starting of the text on the output.

How to remove that space?

I am using a class:

class color:
   RED = '\033[44m' 
   DARKCYAN = '\033[36m'
   CYAN = '\033[96m'
   PURPLE = '\033[95m'
   GREEN = '\033[92m'
   YELLOW = '\033[93m'
   BOLD = '\033[1m'
   END = '\033[0m'

using above:

source_b = "main"
dest_b = "feature"

print(color.YELLOW, 'Listing Differneces Between Branches:', color.BOLD, source_b, 'and', dest_b, color.END)

In the output:

 Listing Differences Between Branches:  main and feature 

not only at starting, but also everywhere trying to use color class...

as you can see a space in between Branches: main as here I used Branches:',color.BOLD,source_b in the code.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Ganesh
  • 21
  • 2
  • 4
  • Have you tried using f-Strings? – b3z Feb 09 '22 at 12:37
  • `print` has a default `sep=' '` so when you pass the color it adds two spaces... – Tomerikoo Feb 09 '22 at 12:39
  • Does this answer your question? [How do I keep Python print from adding newlines or spaces?](https://stackoverflow.com/questions/255147/how-do-i-keep-python-print-from-adding-newlines-or-spaces) – Tomerikoo Feb 09 '22 at 12:41

1 Answers1

1

This is the property of print function. It prints all the arguments, separated by space and it will print a new-line at the end. For example:

print('a', 'b', 'c')

will result in printing a whole line:

a b c

One way to get rid of the space is to override separator for the print function:

print('a', 'b', 'c', sep='')
# out: abc

Another (presumably preferred) way is not to rely on a print function to put together the parameters, but to create the whole string yourself and put the string to the print function as a whole (rather then several separate arguments). You can do it for example:

'a' + 'b' + 'c' + 'd'
'a{}c{}'.format('b', 'd')
f'a{var_x}c{var_y}' # where var_x='b' and var_y='d'

So the last way (so called f-strings) -- and arguably the most modern way -- would look like:

print(f'{color.YELLOW}Listing Differneces Between Branches: {color.BOLD}{source_b} and {dest_b}{color.END}')
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Drecker
  • 1,215
  • 10
  • 24