In python, the print() function prints the output on the screen. By default, the print() function switches to the next line to print a new statement.

Printing the result in the same line in Python 3.x

In python 3, the print() function has an argument end that takes separator as a value and restricts the creation of a new line. By default, the value of the end parameter is '\n' (newline character).

Let us consider a list of strings list_string = ["Welcome", "To", "Chercher Tech"]. The value of the end parameter is set to ' ' white space character. A for loop iterates over the list and prints all the string values in the same line.

list_string = ["Welcome", "To", "Chercher Tech"]
print("list_string", list_string)
for item in list_string:
    print(item, end=" ")

The output of the above code results in

list_string ['Welcome', 'To', 'Chercher Tech']
Welcome To Chercher Tech 

Printing the result in the same line in Python 2.x

In Python 2, the output can be printed on the same line by using a comma at the end of each print statement.

For example, consider a list of strings list_string = ["Welcome", "To", "Chercher Tech"]. The print statement ends with a comma (,). A for loop iterates over the list and prints all the string values in the same line.

list_string = ["Welcome", "To", "Chercher Tech"]
for item in list_string:
    print(item),

The above code gives output as

Welcome To Chercher Tech

Python 2 doesn't have an end parameter, If used it results in SyntaxError. For example,

list_string = ["Welcome", "To", "Chercher Tech"]
for item in list_string:
    print(item, end = " ")

Output

File "main.py", line 5
    print(item, end = " ")
                    ^
SyntaxError: invalid syntax
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions