Python: How to remove external punctuation using regex and ignore the internal punctuation?

时间:2016-10-20 18:56:41

标签: regex python-3.x

Example:

input: @#$abef*&

output: abef

1 个答案:

答案 0 :(得分:0)

I know you've asked about solving using regular expressions, but here is an alternative over-complicated solution using itertools.dropwhile() and str.isalpha():

In [1]: from itertools import dropwhile

In [2]: s = "@#$ab<ghi>ef*&"

In [3]: is_not_alpha = lambda x: not x.isalpha()

In [4]: ''.join(list(dropwhile(is_not_alpha, list(dropwhile(is_not_alpha, s))[::-1]))[::-1])
Out[4]: 'ab<ghi>ef'

Here, we are, basically, applying the "is not alpha" condition from both sides of the string.