Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Regular Expressions in Python Introduction to Regular Expressions Negated Numbers

Richard Lu
Richard Lu
20,185 Points

Negating numbers that are spread out

Hi, I am having trouble finding out how to find numbers that are spread out. An example would be trying to find the numbers 1, 5, 7, 9. The code below finds all the numbers from 5-7, but what If i don't want 6? How would I go about it?

negate.py
import re

string = '1234567890'

good_numbers = re.findall(r'[5-7]', string, re.X)

1 Answer

Dan Johnson
Dan Johnson
40,531 Points

If you're looking to grab the numbers individually you could do something like this:

re.findall(r"1|5|7|9", string)

Or

re.findall(r"[1579]", string)

This will match those digits and prevent grouping them if they're adjacent, e.g. "150" will map to '1' and '5' instead of "15".

Richard Lu
Richard Lu
20,185 Points

Hi Dan,

Thanks for the fast response! The problem I am getting is if I were to do:

string = "1234567890"
re.findall("[^1579]", string)

I'd get back: ['0', '234', '6', '8']

I'd like it to come back as 1 entire string. How do I accomplish this?

Dan Johnson
Dan Johnson
40,531 Points

Since you'll be dealing with separated groups of numbers I'm thinking something like this would be the easiest solution:

"".join(re.findall("[^1579]", string))

This will capture all the matches as before but concatenate them into one string again.

Richard Lu
Richard Lu
20,185 Points

Thanks Dan! I figured that was the easiest way to do it. If only it came back all at once... haha