-1

For example, if there is a sentence "I have 8 pens and my friend have 7 pens" I know how to use re.findall to extract the number and the outcome will be ['8', '7']. However, i want to figure out how many sets of numbers in the sentence, which the answer suppose to be 2. Can someone help me to do it? thank you

Kevin Guo
  • 87
  • 8
  • If you mean to say number of numbers, then you can do like this to get it- `len(re.findall(r'\d+', 'I have 8 pens and my friend have 7 pens'))` – Vikram Singh Chandel Nov 23 '16 at 04:45
  • It's unclear if you mean proper a python `set` of numbers (no duplicates in output), or are using it in a generic "group of numbers" context (duplicates allowed) – ChrisFreeman Nov 23 '16 at 05:30

4 Answers4

3

Simply use the length of the findall() output?

>>> sent =  "I have 8 pens and my friend have 7 pens"
>>> import re
>>> re.findall(r'\d+', sent)
['8', '7']
>>> len(re.findall(r'\d+', sent))
2

Or since you asked for the set of numbers, convert the list to a set too (excluding any doubles).

>>> sent =  "I have 8 pens and my 8 friend have 7 pens"
>>> import re
>>> re.findall(r'\d+', sent)
['8', '8', '7']
>>> len(re.findall(r'\d+', sent))
3
>>> len(set(re.findall(r'\d+', sent)))
2
internetional
  • 312
  • 2
  • 8
ChrisFreeman
  • 5,831
  • 4
  • 20
  • 32
1

To find how many numbers are in a string, you can find the length of the list you created with your re.findall call.

In [1]: import re

In [2]: sentence = "I have 3 tacos, 2 burritos, and 3 tortas"

In [3]: re.findall(r'\d+', sentence)
Out[3]: ['3', '2', '3']

In [4]: len(re.findall(r'\d+', sentence))
Out[4]: 3

To find how many unique numbers are present in the string, convert the list into a set and find the length of that.

In [5]: len(set(re.findall(r'\d+', sentence)))
Out[5]: 2
0

Cant you use len(re.findall()) find the answer.

Vibhutha Kumarage
  • 1,372
  • 13
  • 26
0

If you use

amount = len(re.findall(sentence))
print(amount)

This SHOULD work. Though, I must admit I have never used re.findall, but what it looks like up there is that it creates a list of the numbers. So if the string is in a variable called sentence, and re.findall makes a list of numbers. Then Len should read the length of the list. Then it will print the length of the list.