Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

Firstly, I would like to say I am very new to the language but already got pretty deep in my calculator app for simple physics equations. My plan is to make a home screen with one other calculation screen first, and once that is as good as I can get it to be, I will continue to the rest of the screens.

In this particular screen, (and probably most other ones I'll have to use this function) I've established a custom TextInput that only allows numbers 0-9 and one decimal point. However, I'm currently breaking my head trying to figure out how to include a NEGATIVE SIGN in to my allowed set of inputs.

Here's the code: (I found it open source, I understand the logistics, but I've yet to completely understand the re.compile function)

class FloatInput(TextInput):

pat = re.compile('[^0-9]') <----THIS IS WHERE I TRIED TO ADD ^[+-]? w/ NO LUCK :(

def insert_text(self, substring, from_undo=False):

    pat = self.pat

    if '.' in self.text:

        s = re.sub(pat, '', substring)

    else:

        s = '.'.join([re.sub(pat, '', s) for s in substring.split('.', 1)])

    return super(FloatInput, self).insert_text(s, from_undo=from_undo)

1 Answer

0 votes
by (36.8k points)

If - is escaped (e.g. [a-z]) or if it’s placed as the first or last character (e.g. [-a] or [a-]), it will match a literal '-'.

To get a pattern that matches anything but 0-9, - or +, you need to use:

pat = re.compile('[^0-9\-+]')

 If you are a beginner and want to know more about Data Science the do check out the Data Science course

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...