Klak031
Klak031

Reputation: 155

Removing double whitespace in python when inserting ascii escape characters

How I can remove double whitespace on place where I inserting ascii escape characters. Everything work as I want to but only problem is that double white space in place where I am using escape characters.

class Print(): 
    def  __init__(self, type, content, bold=False, emphasis=False, underline=False, timestamp=True):
        # Set color of the string
        if type == "info":
            self.start = "\033[0m"
        elif type == "error":
            self.start = "\033[91m"
        elif type == "success": 
            self.start = "\033[92m"
        elif type == "warning":
            self.start = "\033[93m"

        # Format style of the string
        if bold:
            self.start += "\033[1m"        
        if emphasis:
            self.start += "\033[3m"
        if underline:
            self.start += "\033[4m"

        # Check for name and format it
        string = content.split(" ")
        formated_string = []
        for word in string:
            if word.startswith("["):
                formated_string.append("\033[96m")
            formated_string.append(word)
            if word.endswith("]"):
                formated_string.append(self.start)

        self.content = " ".join(formated_string)

        # Set color and format to default values
        self.end = "\033[0m"

        # Get current date and time
        stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": "

        print(f"{self.start}{stamp if timestamp == True else ''}{self.content}{self.end}")

this is call when I import my Debug module to my code:

Debug.Print("info", "this is test [string] as example to [my] problem")

and this is result:

2021-11-03 20:16:09: this is test  [string]  as example to  [my]  problem

you can notice double white space infront and after square brackets. Color formating is not visible

Upvotes: 0

Views: 220

Answers (2)

D-E-N
D-E-N

Reputation: 1272

The problem is, that you append the color values as extra elements so it adds 2 spaces because the color values are invisible values but also concat by spaces. (You can print your formated_string to see all values where spaces are added). You can change your code to the folloowing to fix it:

class Print():
    def __init__(self, type, content, bold=False, emphasis=False, underline=False, timestamp=True):
        # Set color of the string
        if type == "info":
            self.start = "\033[0m"
        elif type == "error":
            self.start = "\033[91m"
        elif type == "success":
            self.start = "\033[92m"
        elif type == "warning":
            self.start = "\033[93m"

        # Format style of the string
        if bold:
            self.start += "\033[1m"
        if emphasis:
            self.start += "\033[3m"
        if underline:
            self.start += "\033[4m"

        self.end = "\033[0m"

        # Check for name and format it
        string = content.split(" ")
        formated_string = []
        for word in string:
            if word.startswith("["):
                word = f"\033[96m{word}"
            if word.endswith("]"):
                word = f"{word}{self.end}"
            formated_string.append(word)

        self.content = " ".join(formated_string)

        # Set color and format to default values
        self.end = "\033[0m"

        # Get current date and time
        stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": "

        print(f"{self.start}{stamp if timestamp == True else ''}{self.content}{self.end}")

Upvotes: 1

mrvol
mrvol

Reputation: 2973

>>> ' '.join([a for a in "this is     test [string] as example    to [my] problem".split(' ') if a])
'this is test [string] as example to [my] problem'

Upvotes: 0

Related Questions