Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print statements without new lines in python?

Tags:

python

I was wondering if there is a way to print elements without newlines such as

x=['.','.','.','.','.','.']

for i in x:
    print i

and that would print ........ instead of what would normally print which would be

.
.
.
.
.
.
.
.

Thanks!

like image 322
ollien Avatar asked Aug 25 '12 17:08

ollien


People also ask

How do you enter without a new line in Python?

In short: You can't. raw_input() will always echo the text entered by the user, including the trailing newline. That means whatever the user is typing will be printed to standard output. If you want to prevent this, you will have to use a terminal control library such as the curses module.

How do I keep the print on the same line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call.

What does '\ t 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.


2 Answers

This can be easily done with the print() function with Python 3.

for i in x:
  print(i, end="")  # substitute the null-string in place of newline

will give you

......

In Python v2 you can use the print() function by including:

from __future__ import print_function

as the first statement in your source file.

As the print() docs state:

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Note, this is similar to a recent question I answered ( https://stackoverflow.com/a/12102758/1209279 ) that contains some additional information about the print() function if you are curious.

like image 144
Levon Avatar answered Sep 22 '22 03:09

Levon


import sys
for i in x:
    sys.stdout.write(i)

or

print ''.join(x)
like image 25
applicative_functor Avatar answered Sep 23 '22 03:09

applicative_functor