user3200392
user3200392

Reputation: 605

remove characters from the first items in list of lists

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

Answers (3)

itzMEonTV
itzMEonTV

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

Himanshu dua
Himanshu dua

Reputation: 2523

Check online demo

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

Ami Tavory
Ami Tavory

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

Related Questions