0

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?

user3200392
  • 615
  • 1
  • 9
  • 22

3 Answers3

1

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)
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
1

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.

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
0

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)
Himanshu dua
  • 2,496
  • 1
  • 20
  • 27