Python new line

Python new line

Python new line is a state which is used to mark the end of a line. It can also be referred to as the beginning of a new line in other words. It helps in easy working of files and getting better outputs. There are a number of ways in python to identify new line. One of the easiest ways is by using a backslash with character n β€˜\n’. For an instance, if the user writes β€œHello\nMy name is Megha”. The output of this in python will be:

Hello
My name is Megha

The output will be displayed as this because after using \n, the hold will get passed onto the new line and the rest of the sentence will be displayed in the new line only.

Python New line vs end

As we have discussed above, the new line will take control of the next line. However, β€˜end’ function creates a place for space in the statement. For example, if the user writes the code as:

print("Hello! ", end = '')
print("Welcome to Developer Helps")

The output of the above python code will be:

Hello! Welcome to Developer Helps

Space will add to both the individual lines in the above code. Hence displaying the output in the same line. The end will not just add space to the strings but will also specify the string which user wishes to print inside the given strings.

Check out the python code below to understand where the user can print in the same line using in-built function in python:

print("Hello! "), 
print("Welcome to Developer Helps") 
 
a = [10, 20, 30, 40] 
  
# printing a element in same 
# line 
for x in range(4): 
    print(a[x]),

The output of the above program will be:

Hello! Welcome to Developer Helps
10 20 30 40

Python has another concept for a new line which is by using the python sys module. The user can import the sys module which is a built-in module in python. The next step is to use stdout.write() to print the string. Check out the python code below to see how the sys module can be used in python:

import sys
sys.stdout.write("Hello!")
sys.stdout.write("My name is Megha")

The output of the above python code will be:

Hello!My name is Megha

Leave a comment

Your email address will not be published. Required fields are marked *