如何在 Python 中打印截断的 key-value 对?

How do I print a truncated key-value pair in Python?

我是一个刚开始编码的人,我正在努力解决一个挑战。挑战在于编写一个函数,当给定一个带有标题和 url 的键值对时,该函数将打印一个链接的标题。

如果标题超过 50 个字符,请将标题截断为 50 个字符后跟 3 个省略号。

我正在尝试在 Python 中执行此操作。以下是我到目前为止所拥有的。我意识到最后一部分只是漂浮在那里。不过我不确定把它放在哪里。

我正在尝试创建一个 class,我可以将 key-value 对添加到其中,因为我将不得不在下一个挑战中添加更多。

class Webpage(object):
    def __init__(self, title, link):
        self.title = title
        self.link = link
    ex1 = ('really, really, really long title that will be chopped off', 'example.com')
        print Webpage.ex1

title = (title[:50] + '..' if len(title) > 50 else title)

如有任何帮助,我们将不胜感激。

您可能想为显示的截断标题创建不同的变量,然后使用 @property 到 return 属性 属性。

class Webpage(object):
    def __init__(self, title, link):
        self.title = title
        self.link = link
        self._truncated_title = (self.title[:50] + '..' if len(self.title) > 50 else self.title)
    @property
    def print_title(self):
        """returns the truncated title"""
        return self._truncated_title
example = Webpage('really, really, really long title that will be chopped off', 'example.com')
print(example.print_title)

希望对您有所帮助!

我的直觉是你想要的只是简单的东西,就像这样。

>>> class Webpage(object):
...     def __init__(self, title, link):
...         self.title = title
...         self.link = link
...     def print_title(self):
...         print (self.title[:50] + '..' if len(self.title)>50 else self.title)
... 
>>> webpage_1 = Webpage('little title', 'http://www.somewhere.org')
>>> webpage_1.print_title()
little title
>>> webpage_2 = Webpage('big title' + 50*'-', 'http://www.somewhere.org')
>>> webpage_2.print_title()
big title-----------------------------------------..