1

I was wondering how to convert a list of nested strings into a nested list of strings using string manipulation like .split(), .strip(), and .replace(). A sample would be converting a sequence like (notice the single quote with double quotes):

['"Chipotle"', '"Pho"']

into something like:

[["Chipotle"], ["Pho"]]
2
  • 4
    [[word.strip('"')] for word in inputlist] would do that. This is rather a broad question if you are talking about doing this in general. Commented Nov 6, 2015 at 21:22
  • Do you ever have more than one inner string within the outer strings?, e.g. "'foo','bar'"? If so, you probably want ast.literal_eval, as that will convert multiple comma separated strings into a tuple. Commented Nov 6, 2015 at 21:46

1 Answer 1

2

If your nested strings are in the form of '"A","B","C"', you can use the following:

s.split('"')[1::2]  split by double quote, only odd indices (i.e. between quotes) 

If you want a nested list, you can use this expression inside a list comprehension, like this:

[s.split('"')[1::2] for s in thelist]

where thelist is the original list.

Why only odd indices? It comes from the structure of the string:

0th element of split() result would be part of the string before 1st quote; 1st - between the 1st and 2nd quotes; 2nd - between the 2nd and 3rd, and so on.

We need only the strings between odd (opening) and even (closing) quotes.

Example:

t = ['"1","2","3","4"', '"5","6","7',"8"']
a = [s.split('"')[1::2] for s in t]
print(a)

prints

[['1','2','3','4'],['5','6','7','8']]
Sign up to request clarification or add additional context in comments.

3 Comments

What is s? Please elaborate and explain better and fully (the answer seems to have been abandoned half-way through). Input/ouput/etc.
s is a string (in the form described above, i.e. element of a list).
@Pynchia Thank you! The answer is now more fully explained

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.