How is the original string useful in Python?

I know the raw string r

or operator r

suppresses the meaning of the escape characters, but in what situation would that really be useful?

+3


source to share


3 answers


Raw strings are typically used for regular expressions that must include a backslash.

re.match(r'\b(\w)+', string)  # instead of re.match('(\\w)+', string

      



They are also useful for DOS file paths that would otherwise have to double each path separator.

path = r'C:\some\dir'  # instead of 'C:\\some\\dir'

      

+7


source


They save you from aberrant toothpick syndrome .



a situation in which a quoted expression becomes unreadable because it contains a large number of escape characters, usually a backslash ("\")

+6


source


Raw strings are useful because they save you from adding escape characters just to avoid "escape characters". For example, r'url\1'

equivalent to'url\\1'

0


source







All Articles