在插入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 = "33[0m"
elif type == "error":
self.start = "33[91m"
elif type == "success": 
self.start = "33[92m"
elif type == "warning":
self.start = "33[93m"
# Format style of the string
if bold:
self.start += "33[1m"        
if emphasis:
self.start += "33[3m"
if underline:
self.start += "33[4m"
# Check for name and format it
string = content.split(" ")
formated_string = []
for word in string:
if word.startswith("["):
formated_string.append("33[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 = "33[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

你可以注意到方括号前后有两个空格。颜色格式化不可见

问题是,您将颜色值附加为额外元素,因此它添加了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 = "33[0m"
elif type == "error":
self.start = "33[91m"
elif type == "success":
self.start = "33[92m"
elif type == "warning":
self.start = "33[93m"
# Format style of the string
if bold:
self.start += "33[1m"
if emphasis:
self.start += "33[3m"
if underline:
self.start += "33[4m"
self.end = "33[0m"
# Check for name and format it
string = content.split(" ")
formated_string = []
for word in string:
if word.startswith("["):
word = f"33[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 = "33[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}")
>>> ' '.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'

相关内容

  • 没有找到相关文章

最新更新