-2

What is the best way to get from this:

['\n    62\n    ', '\n    178\n    ', '\n    7,800\n    ']

...to this in Python?

['62', '178', '7,800']

I am trying to strip all non-alphanumeric characters from the strings like below,

import re
re.sub(r'\W+', '', my_string)

...but with lists/arrays.

octosquidopus
  • 3,517
  • 8
  • 35
  • 53
  • @Eric: Thanks. I figured this had to be a dup, but I couldn't find a question with a good answer that would make sense to this OP; that one is perfect. – abarnert Nov 11 '14 at 19:46

3 Answers3

0

Its what that str.strip([chars]) is for ! str.strip Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> l=['\n    62\n    ', '\n    178\n    ', '\n    7,800\n    ']
>>> [i.strip() for i in l]
['62', '178', '7,800']
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

If you want to run a function over every member of an iterable, like a list, you can do that in three ways: an explicit for statement, a call to the map function, or a comprehension.

A comprehension looks like this:

my_new_strings = [re.sub(r'\W+', '', my_string) for my_string in my_strings]

But, even if you read the tutorial sections above, this may not make sense unless you first think about how to write it with an explicit loop:

my_new_strings = []
for my_string in my_strings:
    my_new_string.append(re.sub(r'\W', '', my_string))

A comprehension is basically this pattern condensed. They're nice because they eliminate some boilerplate (which gets in the way of reading code, and provides more places to make mistakes while writing code), can be used in the middle of an expression, and are a little faster. But ultimately, they do the same thing.

abarnert
  • 354,177
  • 51
  • 601
  • 671
0
>>> x=['\n    62\n    ', '\n    178\n    ', '\n    7,800\n    ']
>>> [re.sub('\W+','',i) for i in x ]
['62', '178', '7800']
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52