Cosma Iaffaldano
Cosma Iaffaldano

Reputation: 221

Create a list of substrings from string

I have this string:

"<C (programming language)> <C++ (programming language)> <Programming Languages> <Computer Programming> "

And i want to obtain a list of substrings, like this:

['<C (programming language)>','<C++ (programming language)>','<Programming Languages>','<Computer Programming>']

I tried to use re library python but without success

Upvotes: 1

Views: 552

Answers (2)

Daniel
Daniel

Reputation: 651

This can be done using the re import, although another solution would be to use the split method as shown here:

st = st.split('>')  # splits the string to a list made of elements divided by the '>' sign but deletes the '>' sign
del st[len(st) - 1]  # Splitting your String like we did will add another unneccesary element in the end of the list
st = [i + ">" for i in st]  # adds back the '>' sign to the every element of the list

Hope it helped

Upvotes: 1

tobspr
tobspr

Reputation: 8376

Using regular expressions, you can use:

import re
regexp = re.compile("<[^>]+>")
matches = regexp.findall(my_string)

The regular expression basically matches everything starting with a '<' and ending with a '>'. findall then returns all found matches.

Upvotes: 6

Related Questions