ammad aslam
ammad aslam

Reputation: 39

Slicing strings

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

Upvotes: 2

Views: 162

Answers (3)

user15302270
user15302270

Reputation:

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

Upvotes: 1

josepdecid
josepdecid

Reputation: 1847

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.

Upvotes: 4

JD2775
JD2775

Reputation: 3801

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

Upvotes: 6

Related Questions