-1

So guys, I've been trying to print a string horizontally in the following case, which I iterate through the string and then, I print it. But it doesn't print horizontally. Instead, it prints vertically. My code:

Python Version 2.7.10

for word in "Monty Python":
    print word

The output is:

M
o
n
t
y

P
y
t
h
o
n

I need your help! Thanks in advance!

Community
  • 1
  • 1
PrimeHack
  • 53
  • 1
  • 2
  • 10
  • 4
    this looks vertical to me – njzk2 Aug 09 '15 at 04:48
  • 1
    What are you talking about? You *are* printing it vertically. Horizontally would look like `Monty Python` which would just be `print "Monty Python"` – DJMcMayhem Aug 09 '15 at 04:49
  • Sorry, bad english, not used to it yet. But thanks! – PrimeHack Aug 09 '15 at 04:51
  • If you're printing it horizontally, why do you need to iterate through each character? You can just use: print "Monty Python" – Zak Aug 09 '15 at 04:58
  • What is the output you are trying to generate? What would you print if the code were working the way you want? – Michael Geary Aug 09 '15 at 05:05
  • No, Michael, I just wanted to print Monty Python horizontally, not vertically. I just did it! Thanks! Just needed to insert a comma in the end of the print statement. – PrimeHack Aug 09 '15 at 05:08
  • possible duplicate of [Printing word in one line](http://stackoverflow.com/questions/31822410/printing-word-in-one-line) – Paul Aug 09 '15 at 11:05

4 Answers4

3

You may use print_function from __future__.

CODE 1

from __future__ import print_function
for word in "Monty Python":
    print(word,end=' ')

OUTPUT 1

M o n t y   P y t h o n 

If you don't want space separated OUTPUT, then replace end=' ' with end=''.

CODE 2

from __future__ import print_function
for word in "Monty Python":
    print(word,end='')

OUTPUT 2

Monty Python 
Vineet Kumar Doshi
  • 4,250
  • 1
  • 12
  • 20
2

You don't need any iteration. Just do this:

Horizontally:

print "Monty Python"

Output:

Monty Python

If you really must iterate through it, you should use sys.stdout.write() rather than print, because print will put a newline character at the end of every print statement.

import sys
for letter in "Monty Python":
    sys.stdout.write(letter) 
DJMcMayhem
  • 7,285
  • 4
  • 41
  • 61
1

You can also use the join method to do this.

m= "Monty Python"
k = "".join([word for word in m])

print k
dyao
  • 983
  • 3
  • 12
  • 25
0

You have to try using join keyword like:

print "".join(word for word in "monty python");

output : monty python
Subhash Khimani
  • 427
  • 7
  • 22