user2481422
user2481422

Reputation: 868

Replace in strings of list

I can use re.sub easily in single string like this:

  >>> a = "ajhga':&+?%"
  >>> a = re.sub('[.!,;+?&:%]', '', a)
  >>> a
      "ajhga'"

If I use this on list of strings then I am not getting the result. What I am doing is:

  >>> a = ["abcd:+;", "(l&'kka)"]
  >>> for x in a:
        ...     x = re.sub('[\(\)&\':+]', '', x)
        ... 
  >>> a
      ['abcd:+;', "(l&'kka)"]

How can I strip expressions from strings in list?

Upvotes: 0

Views: 71

Answers (2)

Tok Soegiharto
Tok Soegiharto

Reputation: 329

>>> a = ["abcd:+;", "(l&'kka)"]
>>> a = [re.sub('[\(\)&\':+]', '', x) for x in a]
>>> a
['abcd;', 'lkka']
>>> 

Upvotes: 1

sundar nataraj
sundar nataraj

Reputation: 8702

for index,x in enumerate(a):
    a[index] = re.sub('[\(\)&\':+]', '', x)

Your changing the value but not updating your list. enumerate is function that return tuple (index,value) for each item of list

Upvotes: 0

Related Questions