darsh
darsh

Reputation: 17

How to get particular string from list in python

a=[('https://www.google.co.in/search?q=kite+zerodha&oq=kite%2Cz&aqs=chrome.1.69i57j0l5.4766j0j7&sourceid=chrome&ie=UTF-8', 1), ('https://kite.zerodha.com/', 1), ('https://kite.trade/connect/login?api_key=xyz', 1)]

how to get value of api_key which is xyz from above mentioned a. please help me to write code in python.Thank you

Upvotes: 0

Views: 42

Answers (2)

jose_bacoy
jose_bacoy

Reputation: 12684

This will work too. Hope this helps.

  • Find all items that has the keyword 'api_key' (in url[0]),
  • Split it into columns, delimited by '=' (split by '=')
  • The last entry ([-1]) will be the answer (xyz).
a=[('https://www.google.co.in/search?q=kite+zerodha&oq=kite%2Cz&aqs=chrome.1.69i57j0l5.4766j0j7&sourceid=chrome&ie=UTF-8', 1), ('https://kite.zerodha.com/', 1), ('https://kite.trade/connect/login?api_key=xyz', 1)]
for ky in [url for url in a if 'api_key' in url[0]]:
    print(ky[0].split('=')[-1])


Sample result: xyz

Upvotes: 0

krishna Prasad
krishna Prasad

Reputation: 3812

Just looping over all elements and parsing url to get the api_key, have a look into below code:

from urlparse import urlparse, parse_qs

a=[('https://www.google.co.in/search?q=kite+zerodha&oq=kite%2Cz&aqs=chrome.1.69i57j0l5.4766j0j7&sourceid=chrome&ie=UTF-8', 1), ('https://kite.zerodha.com/', 1), ('https://kite.trade/connect/login?api_key=xyz', 1)]
for value in a:
    if len(value) > 1:
        url = value[0]
        if 'api_key' in parse_qs(urlparse(url).query).keys():
            print parse_qs(urlparse(url).query)['api_key'][0]

output:

xyz

Upvotes: 1

Related Questions