Harald
Harald

Reputation: 21

How to add a string to some items in a list?

I'm new to Python(3) and Beautifulsoup(4), trying to learn webscraping.

I'm scraping a list of members of the Swedish parliament. Almost allt of the names in the output has a (S) beside them (members of Social Democratic Party). The first four names are missing the (S).

Is there some way to add this to every name without it, perhaps with a conditional statement? "If list item doesn't contain "(S)", append it in the end of that list item."

Also, is it possible to format the first names like the bottom ones?

Code:

source = urllib.request.urlopen("https://www.riksdagen.se/sv/ledamoter- 
partier/socialdemokraterna/").read()
soup = bs.BeautifulSoup(source, "lxml")

namn = soup.find_all("span", {"class": "fellow-name"})

for span in soup.find_all("span", {"class": "fellow-name"}):
    resultat = (span.text.strip())
    print(resultat)

The output is:

Stefan Löfven
Anders Ygeman
Annelie Karlsson
Lena Rådström Baastad
Ahlberg, Ann-Christin (S)
Andersson, Johan (S)
Axelsson, Marie (S)
...

Upvotes: 0

Views: 51

Answers (1)

Jongware
Jongware

Reputation: 22457

There is a way: str.endswith.

resultat = span.text.strip()
if not resultat.endswith(' (S)'):
    resultat += ' (S)'

(I removed the surrounding parentheses in the first line; they are not necessary.)

To put a first name at the end with a comma, split the text on spaces and join them again with the first item at the end:

if not ',' in resultat:
    temp_list = resultat.split()
    resultat = ' '.join(temp_list[1:])+', '+temp_list[0]

Result:

Löfven, Stefan (S)
Ygeman, Anders (S)
Karlsson, Annelie (S)
Rådström Baastad, Lena (S)
Ahlberg, Ann-Christin (S)
Andersson, Johan (S)
Axelsson, Marie (S)

Upvotes: 3

Related Questions