doglas
doglas

Reputation: 115

Python: How to make a string to a list using a substring?

For example I have a string like this...

StringA = "a city a street a room a bed"

I want to cut this string using a substring "a " and make a list from it. So the result looks like...

ListA = ["city ", "street " ,"room " ,"bed"]

It would be OK if there are some empty spaces left. How can I do this? Thanks!

Upvotes: 0

Views: 100

Answers (4)

Fejs
Fejs

Reputation: 2888

This will make list from string:

re.split(r'\s*\ba\b\s*', a)

Output should be something like this:

['', 'city', 'cola', 'room', 'bed']

So, to remove empty strings from list You can use:

[item for item in re.split(r'\s*\ba\b\s*', a) if item]

Which will produce:

['city', 'cola', 'room', 'bed']

Upvotes: 0

PJay
PJay

Reputation: 2807

This should also work:

ListA = StringA.split("a ")[1:]

The [1:] after the split statement has been added because the part before the first 'a' (which is '') will be treated as the first element of ListA and you don't want that.

Your output will look exactly like the one you desire:

ListA = ['city ', 'street ', 'room ', 'bed']

Upvotes: 1

fafl
fafl

Reputation: 7387

You can do it in one line:

filter(len, "a city a street a room a bed".split("a "))

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 600059

You can use split:

list_a = string_a.split('a ')

Upvotes: 1

Related Questions