【问题标题】:How do I print a truncated key-value pair in Python?如何在 Python 中打印截断的键值对?
【发布时间】:2017-05-31 18:38:51
【问题描述】:

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

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

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

我正在尝试创建一个可以添加键值对的类,因为我必须在下一个挑战中添加更多内容。

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)

任何帮助将不胜感激。

【问题讨论】:

  • 您编写的代码应该可以工作,您只需将其放入类方法中即可。然后它应该使用self.title 从类中获取标题。
  • 那么您的问题是如何检索网页?
  • @Matti Lyra 输出应该是链接和截断的标题。但是当我运行它时,我得到一个“找不到命令”的错误。
  • @Barmar 我如何将它放在类方法中?
  • def print_title(self): 后跟打印标题的代码。任何关于用 Python 编写类的教程都应该解释这一点。

标签: python key-value truncation


【解决方案1】:

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

>>> 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-----------------------------------------..

【讨论】:

    【解决方案2】:

    您可能希望为显示的截断标题创建一个不同的变量,然后使用@property 返回属性属性。

    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)
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多