user5616520
user5616520

Reputation: 91

python: search for a 5 digit number instead of specific number

Instead of trying to search for 150,00, 200,00, 250,00 300,00 or 1.000,00, 1.100,00 is it possible to compare strings against for example xxx,xx € and x.xxx,xx € regardless of the numbers?

The code that I've gotten from eLRuL works fine, but it's also giving me the format xx,xx. I only want xxx,xx and x.xxx,xx and I would like also to include the euro sign at the end so it should include this xxx,xx € and x.xxx,xx € .

if re.search(r'\d+\.?\d+,?\d+', item['Value']):

Upvotes: 0

Views: 1758

Answers (2)

pazitos10
pazitos10

Reputation: 1709

Yes, there's a way and you have tagged it: "regex" (regular expressions). In Python you can use either re module or regex module.

First you have to create the pattern, in your case:

import re

number = str(<what_you_want_to_search>) #for example 1,000.00 or 100.00
pat = r'(\d,)?\d{3}\.\d{2}' #pattern for xxx.xx and x,xxx.xx numbers
result = re.search(pat, number)
if result:
    print result.string

re.search returns None if there's no match of the expression and an object if there is. Then you can print out what was the string that matches with the pattern.

I strongly recommend you to read the documentation of the package to know exactly how to create your own regex.

Edit:

As you say, the pattern r'\d+.?\d+,?\d+' is working but is matching with xx,xx too. You have to be more specific:

pat = r'(\d,)?\d{3}.\d{2}'

That pattern matches

  1. Numbers with comma at start after the first digit, but optionally because the ? symbol. i.e: x,...
  2. Then there's exactly 3 numbers and a decimal symbol (.)
  3. Last but not least, exactly 2 numbers.

So this pattern matches with x,xxx.xx or xxx.xx expressions as you wanted at first.

Then if you want to match with the Euro symbol(€) you have to add the characters from Sc manually to your pattern.

Upvotes: 2

eLRuLL
eLRuLL

Reputation: 18799

you can use regex:

import re
...

if re.search(r'\d+\.?\d+,?\d+', item['Value']):

Upvotes: 1

Related Questions