Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a raw string useful in Python?

Tags:

python

I know the raw string operator r or R suppresses the meaning of escape characters but in what situation would this really be helpful?

like image 560
thuang Avatar asked Oct 23 '25 04:10

thuang


2 Answers

Raw strings are commonly used for regular expressions which need to include backslashes.

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

They are also useful for DOS file paths, which would otherwise have to double up every path separator.

path = r'C:\some\dir'  # instead of 'C:\\some\\dir'
like image 83
chepner Avatar answered Oct 27 '25 05:10

chepner


They save you from the leaning toothpick syndrome.

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

like image 44
John Coleman Avatar answered Oct 27 '25 04:10

John Coleman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!