3

Using python 3 print(), does not list the repeated data one after the other on the same line?

Let's say you want a message to display on the same line and repeatedly.

example.

my_message = 'Hello'
for i in range(100) :
    print(my_message), 

it IS CURRENTLY printing one below the other.(not what I want)

hello 
hello
hello..... 

but I read in the python book that adding a comma , after print(), should create the desired effect and would make it display side by side

hello hello hello hello..(x100)

why doesn't it do that in Python 3? How do you fix it?

Markus Safar
  • 6,324
  • 5
  • 28
  • 44
LActon
  • 33
  • 1
  • 3
  • the comma thing is only in python 2, because there `print` is a statement like `if`, `for` etc and to indicate that you don't want a new line you need to indicate it with a comma in the end. In python 3, alongside many other thing, they change it to a build-in function that give you more flexibility in how to handle it, take a look at `help(print)` for details. – Copperfield Feb 07 '16 at 02:23

3 Answers3

7

This does not work in Python 3 because in Python 3, print is a function. To get the desired affect, use:

myMessage = "Hello"
for i in range(100):
    print(myMessage, end=" ")

or more concisely:

print(" ".join("Hello" for _ in range(100)))
zondo
  • 19,901
  • 8
  • 44
  • 83
2

Since print() is a function in Python 3, you can pass multiple arguments to it using the *-operator.

You can do this with a tuple:

print(*('Hello' for x in range(100)))

Or with a list (created by a list comprehension):

print(*['Hello' for x in range(100)])

Another way would be to use join():

print(' '.join('Hello' for x in range(100)))

You can also use the end keyword:

for x in range(100):
    print('Hello', end=' ')

In Python 2.x this was possible:

for x in xrange(100):
    print 'Hello',
pp_
  • 3,435
  • 4
  • 19
  • 27
1

In Python 3, simply

print(*('Hello' for _ in range(5)))

There is no need to create a list or to use join.

To have something other than one space between each "Hello", pass the sep argument (note it's keyword-only):

print(*('Hello' for _ in range(5)), sep=', ')

gives you

Hello, Hello, Hello, Hello, Hello
gil
  • 2,086
  • 12
  • 13