Python convert string to tuple/list

 

I have long string with (delimiter) comma separated and want to covert it to tuple or list.

Following is my string:

s = ‘a,b,c,d,e,f,g,h,i,j,k’

Use following command to convert string to tuple:

tuple = tuple(item for item in s.split(',') if item.strip())
print tuple

Output:

(‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’)

Use following command to convert string to list:

list = [item for item in s.split(',') if item.strip()]
print list

Output:

[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s