What's this?
- I'm rereading the Python tutorial for review.
- I'll try to organize the definition and role of "raw strings".
What I learned.
Escape sequences
The particular expressions started from (backslash) are recognized as particular meanings in string.
For example, \t
means Tab, and \n
means LF.
s = 'a\tb\nA\tB' print(s) # => a b # A B
In Python, we can use both single and double quotations to express string, but we cannot usually use single quotations in a single quotation.
Then, by using an escape sequence, we can use single quotations in a single quotation.
(Of course, we can also use a double quotation.)
# s = 'a'b' => SyntaxError: unterminated string literal s = 'a\'b' print(s) # => a'b
Raw strings
Definition
String literals may optionally be prefixed with a letter 'r' or 'R'.
Such strings are called "raw strings".
They treat backslashes as literal characters.
r = r'a\tb\nA\tB' print(r) # => a\tb\nA\tB
Details
Technically, there is no "raw string type", but string literals that can be prefixed with a letter 'r' or 'R'.
print(type(r)) # => <class 'str'>
As defined, raw strings manipulate backslashes as just backslashes, so we can see the difference when converting them into lists.
print(list(s)) # => ['a', "'", 'b'] print(list(r)) # => ['a', '\\', 't', 'b', '\\', 'n', 'A', '\\', 't', 'B']
When we can use it
We can utilize it when manipulating regular expressions.
For instance, we should use \\\\
to match the string \
because String \\
is interpreted as \
and \\
in regular expressions is interpreted as \
.
re — Regular expression operations — Python 3.11.7 documentation
import re text = '\\begin' print(re.search('\\begin', text)) # => None print(re.search('\\\\begin', text)) # => <re.Match object; span=(0, 6), match='\\begin'>
On the contrary, when using raw strings, we can implement it more simply.
text = r'\begin' print(re.search(r'\\begin', text)) # => <re.Match object; span=(0, 6), match='\\begin'>
Impression on Implementation
- I almost got into the swamp of regular expressions...
- I found it difficult that things used casually are manipulated correctly.