Question mark quantifier –
The question mark quantifier matches zero or one occurrences of the pattern to the left of it.
In : import re In : re.findall('python?', 'pytho') Out: ['pytho'] In : re.findall('python?', 'python') Out: ['python'] In : re.findall('python?', 'pythonnnn') Out: ['python']
The question mark ( ? ) in ‘python?’ will match zero or one occurrences of n as n is to the left of it.
Let’s say that you want to match http as well as https, you can use the question mark quantifier.
In : re.findall('https?', 'http , https') Out: ['http', 'https']
Or you may want to match color or colour as people use both.
In : re.findall('colou?r', 'color, colour') Out: ['color', 'colour']
How to match a question mark character ?
If you want to match a question mark character then escape the question mark with a backslash.
In : re.findall('\?' , 'How are you?') Out: ['?']