2

In python, I want to slice strings in a list in such a way that first few characters from that list must be removed/spliced out.

a=['hello', 'things', 'becoming', 'expensive']

How I can remove the first two characters from each string in the list to get the output

['llo', 'ings', 'coming', 'pensive']

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • 2
    Use list comprehension: `a = [s[2:] for s in a] # ['llo', 'ings', 'coming', 'pensive']` – Andrej Kesely Mar 10 '21 at 18:31
  • First read [Understanding slice notation](https://stackoverflow.com/q/509211/2745495) then read [Slice every string in list in Python](https://stackoverflow.com/questions/35314886/slice-every-string-in-list-in-python) – Gino Mempin Mar 11 '21 at 00:30

3 Answers3

6
a=['hello', 'things', 'becoming', 'expensive']
b = []

for word in a:
    b.append(word[2:])


print(b)

Results in:

['llo', 'ings', 'coming', 'pensive']

This piece:

word[2:] 

is saying to start at Index 2 and return everything to the right of it. Indexes start at 0, so the first 2 letters are ignored

JD2775
  • 3,658
  • 7
  • 30
  • 52
4

There are several ways to do it, but the idea behind is the same, treating the string as a sequence of characters and taking from the 3rd one (index 2, as lists start from 0) until the end, using the : range notation.

Iteratively:

for idx, word in enumerate(a):
    a[idx] = word[2:]

Comprehension List:

a = [word[2:] for word in a]

Map

a = list(map(lambda word: word[2:], a))

Possibly, there are other ways, but these are the most common.

josepdecid
  • 1,737
  • 14
  • 25
1
a =['hello', 'things', 'becoming', 'expensive']
for char in  a :
    a[a.index(char)] = char[2:]
print(a)
    
  • Instead of `a.index(char)`, use [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate): `for idx, char in enumerate(a):` – Gino Mempin Mar 11 '21 at 00:35
  • Yeah,it has lot of solution,but this cod is easier. –  Mar 11 '21 at 16:31
  • Thank you, Payam and all others for this wonderful answer. It really worked for me, However, I wonder, why I can't use the same code if all the strings in this list were multiline strings? What would be the modification in this code then???? – ammad aslam Mar 18 '21 at 19:18
  • Thank you, Payam and all others for this wonderful answer. It really worked for me, However, I wonder, why I can't use the same code if all the strings in this list were multiline strings? What would be the modification in this code then???? – ammad aslam Mar 19 '21 at 05:17