Inizia subitoInizia gratis

Write a regular expression

Let's write some regular expressions!

Your task is to create a regular expression matching a valid temperature represented either in Celsius or Fahrenheit scale (e.g. '+23.5 C', '-4 F', '0.0 C', '73.45 F') and to extract all the appearances from the given string text. Positive temperatures can be with or without the + prefix (e.g. '5 F', '+5 F'). Negative temperatures must be prefixed with -. Zero temperature can be used with a prefix or without.

The re module is already imported.

Tips:

  • The + symbol within the square brackets [] matches the + symbol itself (e.g. the regular expression [1a+] matches to '1', 'a', or '+').
  • You can also apply ? to the characters within the square brackets [] to make the set optional (e.g. [ab]? matches to 'a', 'b', or '').

Questo esercizio fa parte del corso

Practicing Coding Interview Questions in Python

Visualizza corso

esercizio interattivo pratico

Prova questo esercizio completando questo codice di esempio.

# Define a pattern to search for valid temperatures in text
pattern = re.compile(____)

# Print the temperatures out
print(re.findall(pattern, text))
Modifica ed esegui il codice