首页 > 解决方案 > 插入ascii转义字符时删除python中的双空格

问题描述

如何在插入 ascii 转义字符的位置删除双空格。一切都按我的意愿工作,但唯一的问题是我使用转义字符的地方有双空格。

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

这是我将Debug模块导入代码时的调用:

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

这是结果:

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

您会注意到方括号前后的双空格。颜色格式不可见

标签: pythonunicode-escapes

解决方案


问题是,您将颜色值附加为额外元素,因此它添加了 2 个空格,因为颜色值是不可见的值,但也由空格连接。(您可以打印您的formated_string以查看添加了空格的所有值)。您可以将代码更改为以下内容以修复它:

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

推荐阅读