booleantrue
booleantrue

Reputation: 129

How to grab name and remove rest of strings from python list

Here is my list which contain name, address and few more texts and I want to grab the name only. How can I do that. I've tried but couldn't get it.

my_list = ['view profile for\nAli Safaei\nlocated at 1010-650 West Georgia St Vancouver', 'view profile for\nBrian M. Baird\nlocated at 103-1185 West Georgia St Vancouver', 'view profile for\nKarim A. Lalani\nlocated at 1308 Alberni St Vancouver', 'view profile for\nNishant Goswami\nlocated at 201-1743 Robson St Vancouver', 'view profile for\nEric P.J. Bussieres\nlocated at 201-1128 Hornby St Vancouver']

And if you want to see the name then you can view by

print(my_list[0])
Output
view profile for
Ali Safaei
located at 1010-650 West Georgia St Vancouver

How can I get that name from this list?

Upvotes: 0

Views: 43

Answers (3)

Comsavvy
Comsavvy

Reputation: 770

You can get all the name in the list by using this function

def name(li):
    def _name(l):
        li_name = l.split('\n')[1]
        return li_name
    return list(map(_name, li))
>>>> name(my_list)
['Ali Safaei', 'Brian M. Baird', 'Karim A. Lalani', 'Nishant Goswami', 'Eric P.J. Bussieres']

Upvotes: 0

Rocco Fortuna
Rocco Fortuna

Reputation: 291

This will give you the list of names: (look for Python list comprehension for details)

names = [entry.splitlines()[1] for entry in my_list]

If you only need the first name you can simply get it as follows:

firs_name = names[0]

Upvotes: 0

RJ Adriaansen
RJ Adriaansen

Reputation: 9619

my_list = ['view profile for\nAli Safaei\nlocated at 1010-650 West Georgia St Vancouver', 'view profile for\nBrian M. Baird\nlocated at 103-1185 West Georgia St Vancouver', 'view profile for\nKarim A. Lalani\nlocated at 1308 Alberni St Vancouver', 'view profile for\nNishant Goswami\nlocated at 201-1743 Robson St Vancouver', 'view profile for\nEric P.J. Bussieres\nlocated at 201-1128 Hornby St Vancouver']
[i.splitlines()[1] for i in my_list]

Output:

['Ali Safaei', 'Brian M. Baird', 'Karim A. Lalani', 'Nishant Goswami', 'Eric P.J. Bussieres']

Upvotes: 3

Related Questions