Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Regular Expressions in Python Introduction to Regular Expressions Negated Numbers

Can someone explain why this outputs the wrong answer?

When I run my code I get, "Bummer! Got: 12347890." Why is the 7 not being excluded, but the 5 and 6 are?

negate.py
import re

string = '1234567890'

good_numbers = re.findall(r'\d[^567]', string)

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

You are very, very close to the solution-- the problem wording wasn't explicit enough (in my opinion), it took me several tries to get it right too.

The way you wrote it re.findall(r'\d[^567]',x), you were "finding" all the matches that are 2 CHARACTER STRINGS where the first character is ANY digit and the second character IS NOT either a 5, 6, or 7.

Thus, it would match '12','34','78','90' if the source string is '1234567890'. It would not match '56', or '67', but would match '78'

What they were looking for were single characters that were NOT 5, 6, or 7. That kind of confused me too. What I thought was they wanted me to return '1234','789

See below:

Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x='1234567890'
>>> import re
>>> re.findall(r'\d[^567]',x)
['12', '34', '78', '90']
>>>

Either one of these solutions would work, but since the lesson was titled "exclusion" the first is correct.

>>> re.findall(r'[^567]',x)
['1', '2', '3', '4', '8', '9', '0']

>>> re.findall(r'[0-4]|[8-9]',x)
['1', '2', '3', '4', '8', '9', '0']

This helped. I figured out the right answer by reading another thread, however I still didn't understand quite why my answer wouldn't be pop out the right numbers. I now realize where I was going wrong. Thanks so much!