What is the difference between 'string' and r'string 'in Python?

8

I was looking at the code in Django, framework in Python, and I came across the following code in the file urls.py .

urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/([0-9]{4})/$', views.year_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]

I did not really understand what this stretch would be

r'^articles/2003'

What is this r that precedes the declaration of string ?

Is it something related to regular expressions?

    
asked by anonymous 13.08.2015 / 14:29

2 answers

10

A better example would be (yours does not make sense to use r ):

r'^articles03'

This works the way it is. The r indicates that the string is raw, so it does not consider special characters. Without the r in the literal backslash would do what is next to be considered a special character. Then it would be considered a 200 in octal in this case and then the numeral 3. The format \nnn is a character represented in octal in the string "normal". Obviously all those backslash control characters are ignored as well.

As you'll soon ask, u can also be used to represent strings in Unicode encoding.

Double quotes do not change anything, unlike PHP. But the quotation marks in triplicate "" "text" "have difference."

    
13.08.2015 / 14:35
8
  

What is this r that precedes the string declaration?

The r before the quotation marks comes from raw , meaning the string will be interpreted as a literal string .

In a raw string, escape characters such as \n , \r , \t and others are not processed.

# No primeiro caso, o trecho 3 será exibido ao invés de ser convertido
# para a representação octal da letra S
raw = r"\directory3"
val = "\directory3"

print(raw)
print(val)

Output:

  

\ directory \ 123

     

\ directoryS

The behavior is similar to the single quotes of PHP and @ in C # .

  

Is it something related to regular expressions?

Not directly related, but regular expressions use \ to escape special characters (which are many). Since some expressions may be conflicting, it is always preferable to use literal strings when working with regex.

    
13.08.2015 / 14:33