python - 插入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
您会注意到方括号前后的双空格。颜色格式不可见
解决方案
问题是,您将颜色值附加为额外元素,因此它添加了 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}")
推荐阅读
- css - 侧面模态全高页眉,正文和页脚不相等
- postgresql - 无法将消息从 Kafka 消费者接收到 Postgres
- django - Django 导入导出添加到现有管理员
- rust - `#![feature(no_core)]` 和 `#![no_core]` 有什么区别?
- mixins - 为混合角色的属性赋值
- swift - 使用新参数初始化 UIImage
- mysql - 如何优化查询以查找具有 15 亿行的 3 列的重复项
- angular - Angular 6 - 错误类型错误:无法读取未定义的属性“值”
- sql - 使用 Python 分析两个 SQL 数据库之间的多个表中的数据
- meteor - 由于银河服务器内存不足,应用程序被终止