0

I am a python newbie and struggle to understand the usefulness of adding a single letter at the start of function's argument. Example is the following code:

reg_pattern = re.compile(r'[a-zA-Z0-9]')

What is the role of r after .compile(?

If I run:

>>> reg_pattern = re.compile(r'[a-zA-Z0-9]')
>>> reg_pattern.findall('Thanks!')

I get:

['T', 'h', 'a', 'n', 'k', 's']

And if I run it without the r, I also get the same output. I also see other letter such as u in different functions.

mallet
  • 2,454
  • 3
  • 37
  • 64
  • 1
    re means regex and r' means raw data no escaping – Sugumar Venkatesan Jul 20 '17 at 11:01
  • 1
    this does not happen generally speaking. It is only for strings and does not have to be a function call. It simply tells Python to interpret the string as it is without paying attention to special characters such as `'\t'` for example. Try `print('\t')` and `print(r'\t')` to see the difference – Ma0 Jul 20 '17 at 11:01
  • 1
    `r` just tells python that the following characters are to be treated as raw characters. In python regex `\n` means new line character. `r` is used to avoid such confusions. – zaidfazil Jul 20 '17 at 11:02
  • [Duplicate](https://stackoverflow.com/questions/4780088/what-does-preceding-a-string-literal-with-r-mean) – Alexander Ejbekov Jul 20 '17 at 11:03
  • 1
    Also see [string prefixes](https://docs.python.org/3/reference/lexical_analysis.html#grammar-token-stringprefix) in the documentation. – Christian König Jul 20 '17 at 11:03
  • 1
    When you use regexes you usually prepend the strings with an `r` to avoid the [backslash plague](https://docs.python.org/3/howto/regex.html#the-backslash-plague). – skrx Jul 20 '17 at 11:10

0 Answers0