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
  • 2,953
  • 16
  • 80
  • 130

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
  • 580
  • 4
  • 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
  • 30,727
  • 7
  • 64
  • 70
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
2

I'd do it like this:

>>> re.findall(r'[a-z]', a, re.IGNORECASE)
['A', 'F']
RichieHindle
  • 258,929
  • 46
  • 350
  • 392
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
  • 111,086
  • 29
  • 224
  • 214
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,566
  • 19
  • 25