简体   繁体   中英

Printing a list in Python3

I am using feedparser to pull some data from a news channel RSS page. There are around 54 title in the page. However I want to print for example 10 details. I tried over and over but i couldn't do that.

Could you help me.

import feedparser

url = ('http://feeds.bbci.co.uk/turkce/rss.xml')
details = feedparser.parse(url)

def news(d):
  n = 0
  for i in d:
    n+=1
    print(n , '.news ')
    print(i.title)
    print(i.link)
    print(' ')

news(details.entries)

You can see the code on live and try:

https://repl.it/repls/AppropriateSufficientMaps#main.py

Thanks

You need to add a condition to check if it needs to print out more of the items.

import feedparser

url = ('http://feeds.bbci.co.uk/turkce/rss.xml')
details = feedparser.parse(url)

def news(d):
  n = 0
  for i in d:
    n+=1
    if n < 10:
        print(n , '.news ')
        print(i.title)
        print(i.link)
        print(' ')
    else:
        break

news(details.entries)

There are multiple ways to do that:

By doing a slice directly in the function:

def news(d):
  n = 0
  for i in d[:10]:
    n+=1
    print(n , '.news ')
    print(i.title)
    print(i.link)
    print(' ')

news(details.entries)

Or when you call the function

def news(d):
  n = 0
  for i in d:
    n+=1
    print(n , '.news ')
    print(i.title)
    print(i.link)
    print(' ')

news(details.entries[:10])

Simple Solution

import feedparser
url = ('http://feeds.bbci.co.uk/turkce/rss.xml')
details = feedparser.parse(url)
def news(d):
    for i in range(1,11):
    print(i,'.news','\n',d[i].title,'\n',d[i].link,end="\n\n")
news(details.entries)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM