2

I am wondering how can I print some strings in a for loop in one line without space between each other.

I know concatenating strings without space in one line, but outside of a for loop:

>>> print('hi'+'hi'+'hi')
hihihi

However, I have no idea how to do that in a for loop.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Jay Wang
  • 2,650
  • 4
  • 25
  • 51

3 Answers3

4
s = ""
for i in range(3):
    s += 'Hi'
print(s)
Georgy
  • 12,464
  • 7
  • 65
  • 73
Elena NNN
  • 217
  • 1
  • 6
1

You can achieve that by skipping print and calling directly stdout:

import sys
for i in range(3):
    sys.stdout.write("Hi")
sys.stdout.write("\n")

Output result is HiHiHi. See also this question for a lengthy discussion of the differences between print and stdout.

Community
  • 1
  • 1
aleju
  • 2,376
  • 1
  • 17
  • 10
1

You can use the print function from Python 3 and specify an end string like this:

# this import is only necessary if you are using Python 2
from __future__ import print_function

for i in range(3):
    print('hi', end='')
print()

Alternatively, sys.stdout.write does not add a newline character by default.

timgeb
  • 76,762
  • 20
  • 123
  • 145