Skip to content Skip to sidebar Skip to footer

How To Split Parts Of A String In A List Based On Predefined Part Of In The String

Plese help me with below question sample_list = ['Ironman.mdc.googlesuite.net', 'Hulk.nba.abc.googlekey.net', 'Thor.web.gg.hh.googlestream.net', 'Antman.googled.net', 'Loki.me

Solution 1:

You can always split each string in the list with '.' and get a new list. In this case, if you are only interested in the first split, you should use the second argument in the split method (which tells the occurrence):

first_list =[x.split('.')[0] for x in sample_list]

For the second list:

second_list =[x.split('.',1)[1] for x in sample_list]

A better way is to iterate only once through the sample_list and get both the lists. As shown below:

first_list, second_list = zip(* [x.split('.',1) forx in sample_list])

Solution 2:

Using a list comprehension along with split:

sample_list = ['Ironman.googlesuite.net', 'Hulk.googlekey.net',
    'Thor.googlestream.net', 'Antman.googled.net', 'Loki.googlesuite.net',
    'Captain.googlekey.net']
result_list1 = [i.split('.')[0] for i in sample_list]
print(result_list1)

This prints:

['Ironman', 'Hulk', 'Thor', 'Antman', 'Loki', 'Captain']

This strategy is to retain, for each input domain, just the component up to, but not including, the first dot separator. For the second list, we can use re.sub here:

result_list2 = [re.sub(r'^[^.]+\.', '', i) for i in sample_list]
print(result_list2)

This prints:

['googlesuite.net', 'googlekey.net', 'googlestream.net', 'googled.net',
 'googlesuite.net', 'googlekey.net']

Solution 3:

thank you for the answers, it does help but what if I have list like this:

sample_list = ['Ironman.mdc.googlesuite.net', 'Hulk.nba.abc.googlekey.net', 'Thor.web.gg.hh.googlestream.net', 'Antman.googled.net', 'Loki.media.googlesuite.net','Captain.googlekey.net']

I would want everything preceeding 'googlesuite.net', 'googlekey.net','googlestream.net' and 'googled.net' in list1 and corresponding prefixes in another list as:

result_list1=['Ironman.mdc', 'Hulk.nba.abc', 'Thor.web.gg.hh', 'Antman', 'Loki.media', 'Captain']

result_list2=['googlesuite.net', 'googlekey.net', 'googlestream.net', 'googled.net', 'googlesuite.net', 'googlekey.net']

Post a Comment for "How To Split Parts Of A String In A List Based On Predefined Part Of In The String"