0

I have a string which is converted from a list like this:

"['station38', 'station28', 'station27', 'station1', 'station0']"

I want to split it by comma and become this:

list_str=['station38', 'station28', 'station27', 'station1', 'station0']

However I can only get this:

>>> line_stations = upstream_str.replace('[', '').replace(']', '').split(',')
["'station38'", "'station28'", "'station27'", "'station1'", "'station0'"]

And I have used strip('"'), however it failed.

So how to get my favorite form? Thank for your reply.

forestbat
  • 453
  • 4
  • 10

2 Answers2

1

You might be better off using a ready-made solution, in this case ast.literal_eval.

>>> from ast import literal_eval
>>> literal_eval("['station38', 'station28', 'station27', 'station1', 'station0']")
['station38', 'station28', 'station27', 'station1', 'station0']

That is because there could be all kinds of cases that an ad-hoc solution probably doesn't cover, e.g., something like "station42'".

fsimonjetz
  • 5,644
  • 3
  • 5
  • 21
1

You're almost there! The quote you want to get rid of isn't ", but '. You can use replace as before:

upstream_str.replace('[', '').replace(']', '').replace("'", "").split(',')

strip() removes a matching character that is at either end of the string. In your case that doesn't work, because before doing split(",") the string is:

"'station38', 'station28', 'station27', 'station1', 'station0'"

Notice that the ' are all over the middle of the string before you split it into a list. strip is useful however, for removing the []:

upstream_str.strip('[]').replace("'", "").split(',')

You can also look at evaluating the string directly to recover the original list in one operation. I advise looking at the StackOverflow thread on literal_eval.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53