Reputation: 605
I have a nested list and in every list the first item is a string that ends with .abc
. I would like to remove all the .abc
characters from my nested list.
Here's what I have got:
x = [['car.abc', 1, 2], ['ship.abc', 3, 4]]
And I would like to my nested list to be the following:
x = [['car', 1, 2], ['ship', 3, 4]]
How can I achieve this?
Upvotes: 0
Views: 1037
Reputation: 20349
Using a simple for loop.
x = [['car.abc', 1, 2], ['ship.abc', 3, 4]]
for i in x:
i[0] = i[0].rsplit(".", 1)[0]
print(x)
Upvotes: 1
Reputation: 2523
x = [['car.abc', 1, 2], ['ship.abc', 3, 4]]
new_x=[]
for lst in x:
temp_lst=[]
for item in lst:
if(str(item)[-4:] == '.abc'):
item = str(item)[:-4]
temp_lst.append(item)
new_x.append(temp_lst)
print(new_x)
Upvotes: 0
Reputation: 76297
Using nested regular expressions and list comprehension:
>>> import re
>>> [[re.sub(r'.abc$', '', e) if isinstance(e, basestring) else e for e in l] for l in x]
[['car', 1, 2], ['ship', 3, 4]]
isinstance(e, basestring)
checks whether e
is a string (see this question).
For a string e
, re.sub(r'.abc$', '', e)
replaces the part you specified
Otherwise e
is untouched
The preceding happens for any element e
in a list l
, for each l
in x
.
Upvotes: 1