Python Regular Expression, Pulling All Letters Out
Is there a better way to pull A and F from this: A13:F20 a='A13:F20' import re pattern = re.compile(r'\D+\d+\D+') matches = re.search(pattern, a) num = matches.group(0) print num[0
Solution 1:
You don't have to use regular expressions, or re
at all. Assuming you want just letters to remain, you could do something like this:
a = "A13:F20"a = filter(lambda x: x.isalpha(), a)
Solution 2:
I'd do it like this:
>>> re.findall(r'[a-z]', a, re.IGNORECASE)
['A', 'F']
Solution 3:
Use a simple list comprehension, as a filter and get only the alphabets from the actual string.
print [charforchar in input_string ifchar.isalpha()]
# ['A', 'F']
Solution 4:
You could use re.sub
:
>>>a="A13.F20">>>re.sub(r'[^A-Z]', '', a) # Remove everything apart from A-Z
'AF'
>>>re.sub(r'[A-Z]', '', a) # Remove A-Z
'13.20'
>>>
Solution 5:
If you're working with strings that all have the same format, you can just cut out substrings:
a="A13:F20"print a[0], a[4]
More on python slicing in this answer: Is there a way to substring a string in Python?
Post a Comment for "Python Regular Expression, Pulling All Letters Out"