1

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']
8
  • 2
    Why not using csv module to load CSV file? Commented Aug 2, 2020 at 15:23
  • 1
    Try txt.split(","); though the csv library should be useful Commented Aug 2, 2020 at 15:23
  • yeah tried x = txt.split(", ") but still same result Commented Aug 2, 2020 at 15:25
  • 1
    Try doing this: list(map(str.strip, txt.split(","))) Commented Aug 2, 2020 at 15:25
  • 1
    txt.split(',') correct, txt.split(', ') incorrect in this context. Commented Aug 2, 2020 at 15:26

4 Answers 4

2

Try this

txt = "east2,east3"

x = txt.split(',')

print(x)

result

['east2','east3']
Sign up to request clarification or add additional context in comments.

2 Comments

Perhaps str.strip would also be useful to account for spaces before/after the comma?
Arvin, do you mean str.strip shall remove extra space if my strings has empty space ?
1

try this:

x = txt.split(",");

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.