Python string "Modifiers"

What are these "modifiers" called python front-ends? I do not understand what they are used for. In addition, since I do not know what they are called, I do not know what to look for to find out about them (or others that may be available, if any).

In this example, what does the ā€œuā€ in front of the string in return mean?

def __unicode__(self): return u'title: %s, text: %s, created:%s, tags: %s' % (self.title, self.text, self.created, self.tags) 

In this example, django urls, what does r mean?

 urlpatterns = patterns('', (r'^admin/',include(admin.site.urls)), ) 

I am learning python and django, and I see them in the examples, but have no explanation of what they represent.

+4
source share
4 answers

"r" indicates a raw string that modifies the shielding behavior. This is useful for regular expressions to make them easier to read. "U" indicates that it is a Unicode string. They are called string literary prefixes .

From the docs:

String literals may optionally have a prefix with the letter "r" or "R"; such lines are called raw lines and use different rules to interpret backslash escape sequences. The prefix 'u' or 'U' makes the string a Unicode string. Unicode strings use the Unicode character set defined by the Unicode Consortium and ISO 10646. Some escape sequences described below are available in Unicode strings. The prefix "b" or "B" is ignored in Python 2; this means that the literal must be a byte literal in Python 3 (for example, when the code is automatically converted from 2to3). The prefix 'u' or 'b' may be followed by the prefix 'r'.

If there is no prefix 'r' or 'R', escape sequences in strings are interpreted according to rules similar to those used by the C standard.

+13
source

They differ between Python 2 and Python 3:

Python 2:

  "hello" # Normal string (8-bit characters) u"hello" # Unicode string r"hello" # Raw string --> Backslashes don't need to be escaped b"hello" # treated like normal string, to ease transition from 2 to 3 

Python 3:

  "hello" # Unicode string b"hello" # Bytes object. Not a string! r"hello" # Raw string --> Backslashes don't need to be escaped u"hello" # Python 3.3, treated like Unicode string, to ease transition from 2 to 3 
+3
source

They are called string literals: http://docs.python.org/reference/lexical_analysis.html#string-literals

Example: r '' is raw and will not have the same screens

+1
source

Use docs, Luke: http://docs.python.org/reference/lexical_analysis.html#string-literals

u = Unicode string (each element is a Unicode code point)

r = raw string (escape strings are just a regular sequence of characters useful for regular expressions)

b / no prefix = byte string (each element is a byte). Note that in python 3, the prefix does not mean a unicode string.

-3
source

Source: https://habr.com/ru/post/1402718/


All Articles