I am trying to input the following list values into the url string below. When I do the following:
tickers = ['AAPL','YHOO','TSLA','NVDA']
url = 'http://www.zacks.com/stock/quote/{}'.format(tickers)`
Python returns
http://www.zacks.com/stock/quote/['AAPL', 'YHOO', 'TSLA', 'NVDA']`
What I would like it to do instead is to iterate through the list and return the following:
http://www.zacks.com/stock/quote/AAPL
http://www.zacks.com/stock/quote/YHOO
http://www.zacks.com/stock/quote/TSLA
http://www.zacks.com/stock/quote/NVDA
Thank you.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Use an input() function to accept the list elements from a user in the format of a string separated by space. Next, use a split() function to split an input string by space. The split() method splits a string into a list.
To convert a list to a string in one line, use either of the three methods: Use the ''. join(list) method to glue together all list elements to a single string. Use the list comprehension method [str(x) for x in lst] to convert all list elements to type string.
We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.
A nifty trick with map
:
url = 'http://www.zacks.com/stock/quote/{}'
tickers = ['AAPL','YHOO','TSLA','NVDA']
list(map(url.format, tickers))
['http://www.zacks.com/stock/quote/AAPL',
'http://www.zacks.com/stock/quote/YHOO',
'http://www.zacks.com/stock/quote/TSLA',
'http://www.zacks.com/stock/quote/NVDA']
Use this:
tickers = ['AAPL','YHOO','TSLA','NVDA']
url = 'http://www.zacks.com/stock/quote/'
['{}{}'.format(url, x) for x in tickers]
Result is:
['http://www.zacks.com/stock/quote/AAPL',
'http://www.zacks.com/stock/quote/YHOO',
'http://www.zacks.com/stock/quote/TSLA',
'http://www.zacks.com/stock/quote/NVDA']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With