Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between r'string' and normal 'string' in python?

What's the difference between r string (r'foobar') and normal string ('foobar') in python? Is r'string' a regex string?

I've tried the following and there isn't any effects on my regex matches:

>>> import re
>>> n = 3
>>> rgx = '(?=('+'\S'*n+'))'
>>> x = 'foobar'
>>> re.findall(rgx,x)
['foo', 'oob', 'oba', 'bar']
>>>
>>> rgx2 = r'(?=('+'\S'*n+'))'
>>> re.findall(rgx2,x)
['foo', 'oob', 'oba', 'bar']
>>>
>>> rgx3 = r'(?=(\S\S\S))'
>>> re.findall(rgx3,x)
['foo', 'oob', 'oba', 'bar']
like image 337
alvas Avatar asked Dec 02 '22 20:12

alvas


1 Answers

r doesn't signify a "regex string"; it means "raw string". As per the docs:

String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.

like image 103
jonrsharpe Avatar answered Dec 05 '22 10:12

jonrsharpe