Stanley Gan
Stanley Gan

Reputation: 481

Remove a pattern in all strings in a list

For example, if I have a list of strings

alist=['a_name1_1', 'a_name1_2', 'a_name1_3']

How do I get this:

alist_changed = ['a_n1_1', 'a_n1_2', 'a_n1_3']

Upvotes: 2

Views: 3875

Answers (2)

NathanAck
NathanAck

Reputation: 351

If you are looking for something that actually needs to be "pattern" based then you can use python's re module and sub the regular expression pattern for what you want.

import re


alist=['a_name1_1', 'a_name1_2', 'a_name1_3']
alist_changed = []

pattern = r'_\w*_'

for x in alist:
    y = re.sub(pattern, '_n1_', x, 1)
    #print(y)
    alist_changed.append(y)


print(alist_changed)

Upvotes: 2

Aleksey Bilogur
Aleksey Bilogur

Reputation: 3846

alist_changed = [s.replace("ame", "") for s in alist]

Upvotes: 4

Related Questions