1

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]
print num[len(num)-1]

output

A F

note: the digits are of unknown length

jason
  • 3,811
  • 18
  • 92
  • 147

5 Answers5

4

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)
vinit_ivar
  • 610
  • 6
  • 16
  • What is the equivalent of your code but for numbers? Some like `filter(lambda x: x.isnumber(), a)`. Could you please link to the reference page. Thanks – jason Apr 27 '14 at 03:11
  • @jason_cant_code: you're looking for `filter(lambda x: x.isdigit(), a)`. [Here's](https://docs.python.org/2/library/stdtypes.html#string-methods) the reference page. – vinit_ivar Apr 27 '14 at 10:06
2

Use a simple list comprehension, as a filter and get only the alphabets from the actual string.

print [char for char in input_string if char.isalpha()]
# ['A', 'F']
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

I'd do it like this:

>>> re.findall(r'[a-z]', a, re.IGNORECASE)
['A', 'F']
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
0

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'
>>> 
devnull
  • 118,548
  • 33
  • 236
  • 227
0

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?

Community
  • 1
  • 1
vastlysuperiorman
  • 1,694
  • 19
  • 27