简体   繁体   中英

How do I turn each element in a list into a string with quotes

I am using PyCharm IDE.

I frequently work with large data sets, and sometimes I have to iterate through each data.

For instance, I have a list

ticker_symbols = [500.SI, 502.SI, 504.SI, 505.SI, 508.SI, 510.SI, 519.SI...]

How do I automatically format each element into a string with quotes, i .e.

ticker_symbols = ['500.SI', '502.SI', '504.SI', '505.SI', '508.SI', '510.SI', '519.SI'...] ?

Is there a short-cut on PyCharm?

You can just do something like:

ticker_symbols = '[500.SI,502.SI,504.SI,505.SI,508.SI,510.SI,519.SI]'
print(ticker_symbols[1:-1].split(','))

Or like your string:

ticker_symbols = '[500.SI, 502.SI, 504.SI, 505.SI, 508.SI, 510.SI, 519.SI]'
print(ticker_symbols[1:-1].split(', '))

Both reproduce:

['500.SI', '502.SI', '504.SI', '505.SI', '508.SI', '510.SI', '519.SI']

You can use list comprehension:

temp_list = ["'{}'".format(x) for x in ticker_symbols]

Result in:

['500.SI', '502.SI', '504.SI',...]

这会将您的列表元素转换为字符串ticker_symbols=str(ticker_symbols[1:-1].split(', '))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM