TransWikia.com

How to select records based on condition from a list?

Stack Overflow Asked by Harish Bhavandla on December 25, 2021

This is my code:

for a in soup.select('a[href*="/title/t"]',href=True):
    titles.append(a.text)
print(titles)

It is returning the below output.

[' n', 'The Shawshank Redemption', ' n', 'The Godfather', ' n', 'The Godfather: Part II', ' n', 'The Dark Knight', ' n', '12 Angry Men', ' n', "Schindler's List", ' n', 'The Lord of the Rings: The Return of the King', ' n', 'Pulp Fiction', ' n', 'Il buono, il brutto, il cattivo', ' n', 'The Lord of the Rings: The Fellowship of the Ring', ' n', 'Fight Club', ' n', 'Forrest Gump', ' n', 'Inception']

But i want my output without break lines ' n'. only the elements of the list should return.

Thanks In advance.

2 Answers

Loop through every second element since it doesn't contain a linebreak.

for i in range(1, len(titles), 2):
    titles.append(a.text)
print(titles)

Answered by AverageHomosapien on December 25, 2021

Put an if condition

for a in soup.select('a[href*="/title/t"]',href=True):
    if a.text.strip(): titles.append(a.text)
print(titles)

Answered by bigbounty on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP