Python Tip #90 (of 365):

Always use raw strings when defining regular expressions

I recommend this in order to:

1. Avoid warnings about invalid escape sequences
2. Avoid accidentally using a real escape sequence
3. Clarify which strings are regular expressions

Raw strings double up backslashes, disallowing escape sequences.

๐Ÿงต (1/2)

#Python #DailyPythonTip

@treyhunner wait, is r"" a raw string? In my head I've always interpreted that was a regular expression "string"
@CodenameTim @treyhunner precisely. Raw means no escape rewriting.

@CodenameTim @treyhunner @sethmlarson yep, it's pure coincidence that the prefix happens to share a letter with "regex", and that preserving backslashes is so useful for regex

https://docs.python.org/3/reference/lexical_analysis.html#raw-strings

2. Lexical analysis

A Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer(also known as the tokenizer). This chapter describes how the lexical analyzer prod...

Python documentation

@SnoopJ @CodenameTim @sethmlarson
I usually introduce r-strings when talking about regular expressions by asking students to guess what the "r" stands for.

They always guess "regular expression", which gives me an opportunity to tell them they *should* associate regular expressions with them and they *can* think of them as regex strings, but technically the "r" stands for "raw" and they're useful outside the context of regexes also.

P.S. f-strings are "fun strings" (thanks to @mariatta)