Slicing strings

Viewed 99

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']

3 Answers
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

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.

a =['hello', 'things', 'becoming', 'expensive']
for char in  a :
    a[a.index(char)] = char[2:]
print(a)
    
Related