Raw strings | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Raw strings

So I want to start this with a big shoutout to David Carroll for helping me tremendously in my last deep-dive into regular expressions, thanks to him I solved a couple more medium and my first hard level code coach! Anyway, I have another little dilemma here with the enigmatic regular expression 😂 What's up with the use of raw strings in regular expressions? The lessons always use them, and as a habit so have I in my little experimentations with it, but why? What is the difference in functionality, and is there a specific use case for a non-raw string?

3rd Jul 2020, 5:47 PM
Randy Ziegler
Randy Ziegler - avatar
4 Answers
+ 9
Randy Ziegler Thanks for the shout out. 🙏 I'm glad I can help someone, somewhere, every once and a while. 😉👌 Regarding this question, to understand the benefit of raw strings, consider how the following line using a standard string results in a blank line: print("\n") # Outputs a line break. This is one of several special characters that uses a backslash to result in something different in the standard output. In this case, it's a line break. To print the actual string literal ( \n ), the backslash would need to be escaped using another backslash as seen below: print("\\n") # Outputs: \n Alternatively, this is equivalent to using the raw string: print(r"\n") # Also outputs: \n And... print(r"\n" == "\\n") # Outputs: True So... raw strings treat special characters as strings literals without requiring the need to escape those special characters. Regex makes use of backslashes and therefore would want to work with the string literals without having to mess with escaping characters.
3rd Jul 2020, 9:06 PM
David Carroll
David Carroll - avatar
+ 4
In this lesson you should find \1 in a raw string: https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2479/ If you print r"\1" and "\1" you'll get 2 different outputs. From this you can conclude that in the lesson if you used standard string instead you would get a different result.
3rd Jul 2020, 6:16 PM
Seb TheS
Seb TheS - avatar
+ 1
Bagon Seb TheS So basically using raw strings is always better?
3rd Jul 2020, 6:33 PM
Randy Ziegler
Randy Ziegler - avatar
+ 1
Awesome, thanks my guy
3rd Jul 2020, 6:47 PM
Randy Ziegler
Randy Ziegler - avatar