How do you use backslash n in Python?

In this tutorial, you will learn how to print Backslash in Python.

In Python, the backslash ( \ ) character is used for Escape Sequence. This means that the backslash character is used to escape characters that have special meaning like a newline or quotes.

In python \n, \t, \v and many more have special meanings.
\n is used to print a new line, \t is used to print a tab space and \v is used as vertical space.

Let us understand this from examples.

  • \n
print("Welcome to\n Code Speedy")

Output:

Welcome to 
 Code Speedy
  • \t
print("Welcome to \tCode Speedy")

Output:

Welcome to      Code Speedy
  • \v
print("Welcome to \vCode Speedy")

Output:

Welcome to                                                                                                                                                                   
           Code Speedy

Escape Backslash in Python

Then the question arises on how to print backslash (\) in python. We just cannot print backslash (\) along with another character, for example, n is just a character but with a backslash (\) in its precedence, it will become a newline character (\n) similarly t with \ as precedence will become \t which is tab space.

The solution to this problem is by escaping \ with another backslash ie \\.

print("\\")

OUTPUT:

\

You may also read:

  • How to escape from \n newline character in python
  • how to escape quotes in python – escape quotes from string

In this short tutorial, we look at how to add a Python new line. We look at the Python new line character and how the other methods can be used.

Table of Contents - Python new line:

  • Python new line
  • Newline character in Python
  • Multi-line string
  • Closing thoughts - Python new line

Python new line:

In programming, it is a common practice to break lines and display content in a new line. This improves the readability of the output. Apart from that, you would frequently come across the new line character a lot while working with files.

Hence it is quite important that you understand how to add a new line and familiarise yourself with how the new line character works. This tutorial is aimed to do the same.

Newline character in Python:

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

Code and Explanation:

str_1 = "Hire the top \n1% freelance developers"

print(str_1)
‘’’Output - Hire the top 
1% freelance developers’’’

As aforementioned, the character after the new line character is printed in a new line.
Different ways to implement this would include either adding it to string directly, or concatenating it before printing it. A common question that beginners have while learning how to apply a new line is - since we are adding it to a string - Why doesn’t Python print “\n” as it is? And how does it know that a new line must be added?

Well, the backslash (“\”) in the new line character is called an escape sequence. Escape sequences are used to add anything illegal to a string. This way Python understands that the following character is not a part of a string and executes it.

Multiline Strings:

Multiline strings are another easy way to print text in a new line. As the name suggests the string itself spans over multiple lines. These strings can be assigned by using either 3 double quotes or 3 single quotes. Python understands that the string is a multiline string and prints it as such.

Code and Explanation:

str_1 = """Hire the top 
1% freelance 
developers"""

print(str_1)

'''Output - Hire the top 
1% freelance 
developers'''

In the above example, the string is printed in the same way as the information was passed.

Closing thoughts - Python new line:

Although both methods can be used in Python to add new lines I would recommend using the first method as it is the most commonly accepted method. Also, given Python has an in-built character that facilitates this it is best to utilize it.

However, please feel free to explore and understand how the multiline method works.

Let us understand the fundamentals of strings in python.

Credits: GangBoard

Strings are a sequence of characters which can be stored either as a constant or a different variable. Strings are considered as a datatype. Typically, programmers must enclose strings in quotation marks for the data to recognized as a string and not a number or variable name. Shown below are some of the most used string methods on a daily basis and are one of the most commonly asked interview questions. Also, the code can be found on my GitHub page.

For example, declaring a string in python:

# Declaring a string variable
string = “This is a python tutorial”
print(string)
This is a python tutorialprint(type(string))<class 'str'>

1. Escape sequence in python using strings

In Python strings, the backslash “ ” is a special character, also called the “escape” character. It is used in representing certain whitespace characters: “\t” is a tab, “\n” is a new line, and “\r” is a carriage return. Finally, “ ” can be used to escape itself: “\” is the literal backslash character. Source Python Tutorial.

# THis is an escape sequence.
string = “This is a \”Google Colab\” python notebook”
print(string)This is a "Google Colab" python notebook

2. Accessing the String by an Index

Strings can be accessed by their index in order to get the value. To do this all you have to do is just place the number (index value) inside the pair of square brackets along with the name of the string.

string = “Python”print(string[2])tprint(string[5])n

3. Slicing a string

Slicing a string helps to get a set of characters from a string. This is really helpful when we want to access a particular set of characters in a string. Below are some slicing variants that are useful.

string = “programming”
string
'programming'

Getting one character of the string

print(string[0:1])p

Getting the first three characters from the string

print(string[0:3])pro

Getting the first three characters from the string (Alternate)

print(string[:3])pro

Getting the last three characters from the string

print(string[-3:])ing

Getting all characters but excluding three first characters from the string

print(string[3:])gramming

Getting all characters but excluding the last three characters from the string

print(string[:-3])programm

Reversing all the characters in a given string

print(string[::-1])gnimmargorp

Alternative to printing all characters in a string

print(string[::])programming

4. Splitting a string

Sometimes splitting a string is a handy option because it is one of the easiest ways to convert a string into a list. I know I have not spoken about the list but keep in mind that split converts a string into a list. You can find the material on Python Lists that is written by me which can provide enough idea to master python lists:

String = “Computer Programming”
String
‘Computer Programming’type(String)strlist = String.split()
list
['Computer', 'Programming']type(list)list

5. Replacing a string

The Replace function in python is one of the best function that can be applied to strings. For example, shown below is a string “Money” we need to replace the dollar and the comma sign and this can be done as shown below.

Money = ‘$113,678’
print(Money)
print(“===========================”)
print(type(Money))
$113,678
===========================
<class ‘str’>
Money = Money.replace(‘$’, ‘’)
Money
‘113,678’Money = Money.replace(‘,’, ‘’)
Money
‘113678’Money = int(Money)
print(Money)
print(“===========================”)
print(type(Money))
113678
===========================
<class ‘int’>

6. Join

The join function is python is used to join the string according to the specified pattern.

String = “Python Programming is fun”
String
‘Python Programming is fun’String = “ “.join(String)
String
‘P y t h o n P r o g r a m m i n g i s f u n’

7. Capitalize

The capitalize function capitalizes the first character in the word or a string.

string = “programming”
string
‘programming’string = string.capitalize()
string
‘Programming’

8. Center

The center method returns a string which is padded with the specified character.

string = “python”
string
‘python’print(string.center(15, ‘*’))*****python****

9. Find

The find method returns the index of the given substring position. If the value is not found it returns, -1.

string = “programming”
string
‘programming’print(string.find(‘p’))0print(string.find(‘t’))-1

10. Strip

The strip function strips or removes the white spaces both from the starting and the ending of a string.

string = “     programming is easy    “
string
‘ programming is easy ‘print(string.strip())programming is easy

Hence above are the very important techniques or functions of Strings in Python. Some of the examples were referred from Python Strings. I have written this tutorial in a simple way such that everybody can understand and master the concepts of Strings in Python without prior programming knowledge or experience. If you guys have some doubts in the code, the comment section is all yours.

Thank you

What does backslash n mean in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

What is the '\ n escape character?

Escape sequences are used inside strings, not just those for printf, to represent special characters. In particular, the \n escape sequence represents the newline character.

What does \r indicate in Python?

The r means that the string is to be treated as a raw string, which means all escape codes will be ignored. For an example: '\n' will be treated as a newline character, while r'\n' will be treated as the characters \ followed by n .