【发布时间】:2019-03-16 21:44:51
【问题描述】:
下面的类允许创建和编辑文本对象具有三种方法 - write() 将新文本添加到现有文本,set_font 将方括号中的新字体名称添加到文本的开头和结尾, show() 只是打印文本:
import re
class Text:
def __init__(self):
self.content = ''
def write(self, text):
match = re.search(r'\[[^\]]*\]$', self.content, re.IGNORECASE)
if match:
font_name = match.group(0)
self.content = font_name + self.content.replace(font_name, '') + text + font_name
else:
self.content += text
def set_font(self, font_name):
new_font = "[{}]".format(font_name)
match = re.match(r'\[[^\]]*\]', self.content, re.IGNORECASE)
if match:
old_font = match.group(0)
self.content = self.content.replace(old_font, new_font)
else:
self.content = new_font + self.content + new_font
def show(self):
print(self.content)
当我在下面的代码中创建和操作对象时,它似乎按预期工作,但它没有通过下面的断言测试,即使它似乎输出了与@987654325 中的结果字符串相同的结果字符串@ 陈述。 你能帮我看看我错过了什么吗?
text = Text()
text.write("At the very beginning ")
text.set_font("Arial")
text.write("there was nothing.")
assert text.show() == "[Arial]At the very beginning there was nothing.[Arial]"
【问题讨论】: