Escape Sequencing in Python

While printing Strings with single and double quotes in it causes SyntaxError because String already contains Single and Double Quotes and hence cannot be printed with the use of either of these. Hence, to print such a String either Triple Quotes are used or Escape sequences are used to print Strings. 

Escape sequences start with a backslash and can be interpreted differently. If single quotes are used to represent a string, then all the single quotes present in the string must be escaped and the same is done for Double Quotes.

Python
# Initial String
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)

# Escaping Single Quote
String1 = 'I\'m a "Geek"'
print("\nEscaping Single Quote: ")
print(String1)

# Escaping Double Quotes
String1 = "I'm a \"Geek\""
print("\nEscaping Double Quotes: ")
print(String1)

# Printing Paths with the
# use of Escape Sequences
String1 = "C:\\Python\\Geeks\\"
print("\nEscaping Backslashes: ")
print(String1)

# Printing Paths with the
# use of Tab
String1 = "Hi\tGeeks"
print("\nTab: ")
print(String1)

# Printing Paths with the
# use of New Line
String1 = "Python\nGeeks"
print("\nNew Line: ")
print(String1)

Output:

Initial String with use of Triple Quotes: 
I'm a "Geek"
Escaping Single Quote: 
I'm a "Geek"
Escaping Double Quotes: 
I'm a "Geek"
Escaping Backslashes: 
C:\Python\Geeks\
Tab: 
Hi    Geeks
New Line: 
Python
Geeks

Example:

To ignore the escape sequences in a String, r or R is used, this implies that the string is a raw string and escape sequences inside it are to be ignored.

Python
# Printing hello in octal
String1 = "\110\145\154\154\157"
print("\nPrinting in Octal with the use of Escape Sequences: ")
print(String1)

# Using raw String to
# ignore Escape Sequences
String1 = r"This is \110\145\154\154\157"
print("\nPrinting Raw String in Octal Format: ")
print(String1)

# Printing Geeks in HEX
String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting in HEX with the use of Escape Sequences: ")
print(String1)

# Using raw String to
# ignore Escape Sequences
String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting Raw String in HEX Format: ")
print(String1)

Output:

Printing in Octal with the use of Escape Sequences: 
Hello
Printing Raw String in Octal Format: 
This is \110\145\154\154\157
Printing in HEX with the use of Escape Sequences: 
This is Geeks in HEX
Printing Raw String in HEX Format: 
This is \x47\x65\x65\x6b\x73 in \x48\x45\x58

Python String

A String is a data structure in Python Programming that represents a sequence of characters. It is an immutable data type, meaning that once you have created a string, you cannot change it. Python String are used widely in many different applications, such as storing and manipulating text data, representing names, addresses, and other types of data that can be represented as text.

Table of Content

  • What is a String in Python?
  • Create a String in Python
  • Accessing characters in Python String
  • String Slicing
  • Python String Reversed
  • Deleting/Updating from a String
  • Escape Sequencing in Python
  • Python String Formatting
  • Useful Python String Operations  
  • Python String constants 
  • Deprecated string functions
  • FAQ’s on Python String

Similar Reads

What is a String in Python?

Python Programming does not have a character data type, a single character is simply a string with a length of 1. Let’s see the Python string syntax:...

Create a String in Python

Strings in Python can be created using single quotes or double quotes or even triple quotes. Let us see how we can define a string in Python or how to write string in Python....

Accessing characters in Python String

In Python Programming tutorials, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on....

String Slicing Python

In Python Programming tutorials, the String Slicing method is used to access a range of characters in the String. Slicing in a String is done by using a Slicing operator, i.e., a colon (:).  One thing to keep in mind while using this method is that the string returned after slicing includes the character at the start index but not the character at the last index....

Python String Reversed

In Python Programming tutorials, By accessing characters from a string, we can also reverse strings in Python Programming. We can Reverse a string by using String slicing method....

Deleting/Updating from a String

In Python, the Updation or deletion of characters from a String is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. Although deletion of the entire String is possible with the use of a built-in del keyword. This is because Strings are immutable, hence elements of a String cannot be changed once assigned. Only new strings can be reassigned to the same name....

Escape Sequencing in Python

While printing Strings with single and double quotes in it causes SyntaxError because String already contains Single and Double Quotes and hence cannot be printed with the use of either of these. Hence, to print such a String either Triple Quotes are used or Escape sequences are used to print Strings....

Python String Formatting

Strings in Python or string data type in Python can be formatted with the use of format() method which is a very versatile and powerful tool for formatting Strings. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order....

Useful Python String Operations

Logical Operators on StringString Formatting using %String Template ClassSplit a stringPython DocstringsString slicingFind all duplicate characters in stringReverse string in Python (5 different ways)Python program to check if a string is palindrome or not...

Python String constants

Built-In Function Description string.ascii_lettersConcatenation of the ascii_lowercase and ascii_uppercase constants. string.ascii_lowercaseConcatenation of lowercase letters string.ascii_uppercaseConcatenation of uppercase letters string.digitsDigit in strings string.hexdigitsHexadigit in strings string.letters concatenation of the strings lowercase and uppercase string.lowercase A string must contain lowercase letters. string.octdigits Octadigit in a string string.punctuation ASCII characters having punctuation characters. string.printable String of characters which are printable String.endswith()Returns True if a string ends with the given suffix otherwise returns False String.startswith()Returns True if a string starts with the given prefix otherwise returns False String.isdigit()Returns “True” if all characters in the string are digits, Otherwise, It returns “False”. String.isalpha()Returns “True” if all characters in the string are alphabets, Otherwise, It returns “False”. string.isdecimal()Returns true if all characters in a string are decimal. str.format()one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. String.indexReturns the position of the first occurrence of substring in a string string.uppercase A string must contain uppercase letters. string.whitespaceA string containing all characters that are considered whitespace. string.swapcase()Method converts all uppercase characters to lowercase and vice versa of the given string, and returns it replace()returns a copy of the string where all occurrences of a substring is replaced with another substring....

Deprecated string functions

Built-In Function Description string.IsdecimalReturns true if all characters in a string are decimal String.IsalnumReturns true if all the characters in a given string are alphanumeric. string.IstitleReturns True if the string is a title cased string String.partitionsplits the string at the first occurrence of the separator and returns a tuple. String.IsidentifierCheck whether a string is a valid identifier or not. String.lenReturns the length of the string. String.rindexReturns the highest index of the substring inside the string if substring is found. String.MaxReturns the highest alphabetical character in a string. String.minReturns the minimum alphabetical character in a string. String.splitlinesReturns a list of lines in the string. string.capitalizeReturn a word with its first character capitalized. string.expandtabsExpand tabs in a string replacing them by one or more spaces string.findReturn the lowest indexing a sub string. string.rfindfind the highest index. string.countReturn the number of (non-overlapping) occurrences of substring sub in string string.lowerReturn a copy of s, but with upper case, letters converted to lower case. string.splitReturn a list of the words of the string, If the optional second argument sep is absent or None string.rsplit()Return a list of the words of the string s, scanning s from the end. rpartition()Method splits the given string into three parts string.splitfields Return a list of the words of the string when only used with two arguments. string.joinConcatenate a list or tuple of words with intervening occurrences of sep. string.strip()It returns a copy of the string with both leading and trailing white spaces removed string.lstripReturn a copy of the string with leading white spaces removed. string.rstripReturn a copy of the string with trailing white spaces removed. string.swapcaseConverts lower case letters to upper case and vice versa. string.translateTranslate the characters using table string.upperlower case letters converted to upper case. string.ljustleft-justify in a field of given width. string.rjustRight-justify in a field of given width. string.center()Center-justify in a field of given width. string-zfillPad a numeric string on the left with zero digits until the given width is reached. string.replaceReturn a copy of string s with all occurrences of substring old replaced by new. string.casefold()Returns the string in lowercase which can be used for caseless comparisons. string.encodeEncodes the string into any encoding supported by Python. The default encoding is utf-8. string.maketransReturns a translation table usable for str.translate()...

FAQ’s on Python String

Q.What is a Python string?...