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

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:

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

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

>Solution :

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}")
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