2017-05-31 58 views
0

我刚刚开始编码,我试图解决一个挑战。面临的挑战是编写一个函数,当给定一个具有标题和url的键值对时,该函数将打印一个链接标题。如何在Python中打印截断的键值对?

如果标题长度超过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) 

任何帮助,将不胜感激。

+0

您编写的代码应该可以工作,您只需将其放入类方法即可。然后它应该使用'self.title'来从课程中获得标题。 – Barmar

+0

所以你的问题如何检索网页? –

+0

@Matti Lyra输出应该是链接和截断标题。但是当我运行它时,我得到一个“找不到命令”的错误。 –

回答

0

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

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

您可能希望为显示的截断标题创建一个不同的变量,然后使用@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) 

希望这有助于!