如何将列表中的值输入字符串?

时间:2018-02-15 13:05:31

标签: python string list format

我正在尝试将以下列表值输入到下面的url字符串中。 当我执行以下操作时:

tickers = ['AAPL','YHOO','TSLA','NVDA']
url = 'http://www.zacks.com/stock/quote/{}'.format(tickers)`

Python返回

http://www.zacks.com/stock/quote/['AAPL', 'YHOO', 'TSLA', 'NVDA']`

我希望它做的是迭代列表并返回以下内容:

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

谢谢。

6 个答案:

答案 0 :(得分:7)

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']

答案 1 :(得分:5)

使用此:

tickers = ['AAPL','YHOO','TSLA','NVDA']
url = 'http://www.zacks.com/stock/quote/'
['{}{}'.format(url, x) for x in 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']

答案 2 :(得分:2)

使用循环遍历tickers,并将字符串连接在一起:

tickers = ['AAPL','YHOO','TSLA','NVDA']
url = 'http://www.zacks.com/stock/quote/'

for ticker in tickers:
   print(url + ticker)

# 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

或者列表理解:

[url + ticker for ticker in 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']

答案 3 :(得分:2)

在传递列表之前,您需要先加入列表。如果您尝试将一个包含所有参数的网址添加到网址中,请先执行此操作:

params = "".join(tickers)
url = 'http://www.zacks.com/stock/quote/{}'.format(params)

如果您想要多个网址,每次都有一个参数:

urls = []
for param in tickers:
    urls.append('http://www.zacks.com/stock/quote/{}'.format(param))

答案 4 :(得分:1)

你可以试试这个:

tickers = ['AAPL','YHOO','TSLA','NVDA']
url = 'http://www.zacks.com/stock/quote/'
for e in tickers:
    print(url + e)

这将打印网址,而不是将它们添加到列表中。

答案 5 :(得分:0)

试试这个: -

tickers = ['AAPL','YHOO','TSLA','NVDA']
url = 'http://www.zacks.com/stock/quote/'
new_ls = (x+y for x,y in zip([url]*len(tickers),tickers))
for new_url in new_ls:
    print(new_url)