Escape Sequences And Raw Strings Python

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 69:-  Escape Sequences And Raw Strings Python

In Python, escape sequences are special sequences of characters that are used to represent certain non-printable or special characters within strings. They are denoted by a backslash \ followed by a specific character. Escape sequences allow you to include characters in strings that would otherwise be challenging to represent directly.

Here are some common escape sequences in Python:

  1. Newline \n: Inserts a newline character, which starts a new line.

pythonCopy code

print("Line 1\nLine 2") # Output: # Line 1 # Line 2

  1. Tab \t: Inserts a horizontal tab (indent).

pythonCopy code

print("Name:\tJohn") # Output: # Name:   John

  1. Backslash \\: Inserts a single backslash character.

pythonCopy code

print("This is a backslash: \\") # Output: # This is a backslash: \

  1. Single Quote \': Inserts a single quote character.

pythonCopy code

print('He said, \'Hello!\'') # Output: # He said, 'Hello!'

  1. Double Quote \": Inserts a double quote character.

pythonCopy code

print("She said, \"Hi!\"") # Output: # She said, "Hi!"

If you want to create a string that contains a lot of backslashes, such as regular expressions or file paths, using escape sequences can lead to a lot of backslashes. To avoid this, you can use a "raw string" by prefixing the string with an 'r' or 'R'. Raw strings treat backslashes as regular characters and do not interpret them as escape sequences.

Here's an example of a raw string:

pythonCopy code

raw_string = r"C:\Users\Documents\file.txt" print(raw_string) # Output: # C:\Users\Documents\file.txt

In the raw string, the backslashes are treated as regular characters, and you don't need to escape them with additional backslashes.

Escape sequences and raw strings are useful in various situations when dealing with strings, especially when handling paths, regular expressions, or any content that includes special characters. They help to ensure that the strings are interpreted and displayed correctly.

8. String

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?