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

5 Answers 5

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

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_cant_code: you're looking for filter(lambda x: x.isdigit(), a). Here's the reference page.
2

I'd do it like this:

>>> re.findall(r'[a-z]', a, re.IGNORECASE) ['A', 'F'] 

Comments

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'] 

Comments

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' >>> 

3 Comments

@RichieHindle I couldn't read the mind since the desired output wasn't posted.
sorry i just edited the question to make it more clear.
@RichieHindle I'm sure, I could have! Thanks for enlightening.
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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.