Michael Jerzy Regdosz
Michael Jerzy Regdosz

Reputation: 21

Python: Splitting a string in a list

I am having trouble splitting an '&' in a list of URL's. I know it is because I cannot split a list directly but I cannot figure out how to get around this error. I am open for any suggestions.

def nestForLoop():
    lines = open("URL_leftof_qm.txt", 'r').readlines()
    for l in lines:
        toke1 = l.split("?")
        toke2 = toke1.split("&")
        for t in toke2:
            with open("ampersand_right_split.txt".format(), 'a') as f:
                    f.write
    lines.close()

nestForLoop() 

Upvotes: 0

Views: 120

Answers (2)

abarnert
abarnert

Reputation: 365717

As Ignacio points out, you should not be doing this in the first place. But I'll explain where you're going wrong, and how to fix it:

toke2 is a list of two strings: the main URL before the ?, and the query string after the &. You don't want to split that list, or everything in that list; you just want to split the query string. So:

mainurl, query = l.split("?")
queryvars = query.split("&")

What if you did want to split everything in the first list? There are two different things that could mean, which are of course done differently. But both require a loop (explicit, or inside a list comprehension) over the first list. Either this:

tokens = [toke2.split("&") for toke2 in l.split("?")]

or

tokens = [token for toke2 in l.split("?")
          for token in toke2.split("&")]

Try them both out to see the different outputs, and hopefully you'll understand what they're doing.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

NO. STOP.

qs = urlparse.urlparse(url).query
qsl = urlparse.parse_qsl(qs)

Upvotes: 8

Related Questions