Jane
Jane

Reputation: 21

Extract certain values from a list

I'm pretty new to Python and only want to extract the city for these clients' addresses:

clients = ["Peter, Calle Fantasia 15, Madrid", "Robert, Plaza de Perdas 2, 
            Sevilla", "Paul, Calle Polo, Madrid", "Francesco, Plaza de Opo I, Segovia"]

Can someone help? Thank you very much in advance!

Upvotes: 2

Views: 127

Answers (3)

yatu
yatu

Reputation: 88226

You can use a list comprehension, and keep the last element in each string starting from the lst , onwards.

For that use string.split setting , as a separator, which will split each string whenever there is a comma, slice the resulting lists keeping the last element, and use string.strip to remove leading white spaces:

clients = ["Peter, Calle Fantasia 15, Madrid", "Robert, Plaza de Perdas 2, 
            Sevilla", "Paul, Calle Polo, Madrid", "Francesco, Plaza de Opo I, Segovia"]

[i.split(',')[-1].strip() for i in clients]
# ['Madrid', 'Sevilla', 'Madrid', 'Segovia']

For more details on the methods used above, I'd suggest you give a look at:

Upvotes: 4

sahasrara62
sahasrara62

Reputation: 11228

without using list comprehension

clients = ["Peter, Calle Fantasia 15, Madrid", "Robert, Plaza de Perdas 2, Sevilla", "Paul, Calle Polo, Madrid", "Francesco, Plaza de Opo I, Segovia"]
list_of_cities =[]
for i in clients:
    index_last_comma = 0
    for j in range(len(i)-1,0,-1):
        if i[j]==',':
            index_last_comma  = j
            break
    city = i[j+1:len(i)].strip()
    list_of_cities.append(city)

print(list_of_cities)
# output ['Madrid', 'Sevilla', 'Madrid', 'Segovia']

Upvotes: 0

iacob
iacob

Reputation: 24171

If the elements of clients are always of the format "name, address, city", you can split it like so:

# List comprehension, splits each element of client on commas,
# then takes the final element (stripping any whitespace)
clients = [client.split(',')[-1].strip() for client in clients]

>>> print(clients)

['Madrid', 'Sevilla', 'Madrid', 'Segovia']

Upvotes: 2

Related Questions