从字符串创建子字符串列表
Create a list of substrings from string
我有这个字符串:
"<C (programming language)> <C++ (programming language)> <Programming Languages> <Computer Programming> "
我想获取一个子字符串列表,如下所示:
['<C (programming language)>','<C++ (programming language)>','<Programming Languages>','<Computer Programming>']
我尝试使用 re 库 python 但没有成功
使用正则表达式,你可以使用:
import re
regexp = re.compile("<[^>]+>")
matches = regexp.findall(my_string)
正则表达式基本上匹配所有以“<”开头和以“>”结尾的内容。 findall
然后 returns 所有找到的匹配项。
这可以使用重新导入来完成,尽管另一种解决方案是使用此处所示的拆分方法:
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
希望对您有所帮助
我有这个字符串:
"<C (programming language)> <C++ (programming language)> <Programming Languages> <Computer Programming> "
我想获取一个子字符串列表,如下所示:
['<C (programming language)>','<C++ (programming language)>','<Programming Languages>','<Computer Programming>']
我尝试使用 re 库 python 但没有成功
使用正则表达式,你可以使用:
import re
regexp = re.compile("<[^>]+>")
matches = regexp.findall(my_string)
正则表达式基本上匹配所有以“<”开头和以“>”结尾的内容。 findall
然后 returns 所有找到的匹配项。
这可以使用重新导入来完成,尽管另一种解决方案是使用此处所示的拆分方法:
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
希望对您有所帮助