Why does this code not return the temperature information that I am looking for?

88 Views Asked by At
def temperature():
    r = requests.get('https://api.darksky.net/forecast/b02b5107a2c9c27deaa3bc1876bcee81/1.312914,%20103.780257')
    json_object = r.text

    regexCurrentTemp = re.compile(r'"temperature":(\d\d.\d\d)')
    moTemp = regexCurrentTemp.search(str(json_object))

    regexApparentTemp = re.compile(r'"apparentTemperature":(\d\d.\d\d)')
    moApparent = regexApparentTemp.search(str(json_object))

    print('The current temperature is %s and the apparent temperature is %s' % (moTemp.group, moApparent.group))

temperature()

When I remove the .groups from print('The current temperature is %s and the apparent temperature is %s' % (moTemp.group, moApparent.group)), it prints a highly unformatted string for me.

Edit:

With .group: The current temperature is <re.Match object; span=(662, 681), match='"temperature":85.87'> and the apparent temperature is <re.Match object; span=(239, 266), match='"apparentTemperature":99.26'>

Without .group:

The current temperature is <built-in method group of re.Match object at 0x75ab9560> and the apparent temperature is <built-in method group of re.Match object at 0x75ab95

1

There are 1 best solutions below

0
On

You need to call group(subgroup) to print the actual value of the match. Check out the documentation.

print('The current temperature is %s and the apparent temperature is %s' % (moTemp.group(1), moApparent.group(1)))

#The current temperature is 86.53 and the apparent temperature is 98.18

.group(0) or .group() returns: 

#The current temperature is "temperature":86.55 and the apparent temperature is "apparentTemperature":99.33