asp
asp

Reputation: 855

How to convert python text string to List?

Trying to convert a string in csv to list item

Here it is what I am trying:

txt = "east2,east3"

x = txt.split()

print(x)

Tried the below as well, still get same result:

txt = "east2,east3"

x = txt.split(", ")

print(x)

Output:

['east2,east3']

Expected:

['east2','east3']

Upvotes: 1

Views: 110

Answers (4)

Ujjwal Dash
Ujjwal Dash

Reputation: 823

Hey You are doing a small mistake in txt.split()

You are doing

x = txt.split(", ")# here you are giving an extra space

Corrected code

x = txt.split(",")# remove the extra space

Upvotes: 1

Anshika Singh
Anshika Singh

Reputation: 1044

The split() method of strings is used to convert the input into lists based on the argument passed.

For example:

inp="2 3 4"
lis=inp.split()
print(lis)

The output is:

[2,3,4]

The default argument for split() is space or " "

When we change this:

inp="2,3,4"
lis=inp.split(",")
print(lis)

The result is:

[2,3,4]

Thus your code can be :

txt = "east2,east3"

x = txt.split(",")

print(x)

This will give the desired output:

['east2','east3']

Upvotes: 1

reyad
reyad

Reputation: 1432

try this:

x = txt.split(",");

Upvotes: 1

Umutambyi Gad
Umutambyi Gad

Reputation: 4101

Try this

txt = "east2,east3"

x = txt.split(',')

print(x)

result

['east2','east3']

Upvotes: 2

Related Questions