Victor Toh
Victor Toh

Reputation: 35

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?

Upvotes: 0

Views: 1021

Answers (3)

SajanGohil
SajanGohil

Reputation: 969

This will convert your list elements to stringsticker_symbols=str(ticker_symbols[1:-1].split(', '))

Upvotes: 0

mastisa
mastisa

Reputation: 2083

You can use list comprehension:

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

Result in:

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

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71610

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

Upvotes: 2

Related Questions