Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I input values from a list into a string?

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.

like image 520
michael0196 Avatar asked Feb 15 '18 13:02

michael0196


People also ask

How do you go from a list to a string?

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.

How do you input a list into a string in Python?

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.

How do I convert a list to a string in one line?

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.

How do I convert a list to a string in Java?

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.


2 Answers

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']
like image 97
cs95 Avatar answered Oct 01 '22 07:10

cs95


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']
like image 33
CezarySzulc Avatar answered Oct 01 '22 08:10

CezarySzulc