Aversace
Aversace

Reputation: 1

Combine Multiple Lines of Output?

I am currently working on a basic Pig Latin translator as one of my first projects, it has been going pretty smooth until I got to translating multiple words. The input is raw_input().split() to create a list that can be easily used in a loop.

def sentfunc(x):
    if len(x) > 0:
        for word in x:
            first = word[0]
            new_sent = word + first + pyg
            new_sent = new_sent[1:len(new_sent)]
            print new_sent

I have tried .join() and also tried other methods listed on Overflow. I figured .join() wouldn't work because it is a loop for each word. Can anyone help me out? Sorry if I look dumb for asking this, I'm new 😅

Upvotes: 0

Views: 296

Answers (4)

gilch
gilch

Reputation: 11681

print is a convenience for writing text to a "file", (stdout by default, but you can specify a different one).

But if you import stdout from sys, you can call its .write() method directly, which gives you more control. Unlike print, it doesn't add a newline for you. (Note that due to buffering, you may have to call .flush() before you see it in the console.)

Upvotes: 0

Liam
Liam

Reputation: 317

Instead of printing every iteration, you can create a list, then append each word to that list. You can then join the list and print the result.

def sentfunc(x):
    result = []
    
    if len(x) > 0:
        for word in x:
            first = word[0]
            new_sent = word + first + pyg
            new_sent = new_sent[1:len(new_sent)]
            result.append(new_sent)
    
    print ' '.join(result)

Note that this is also noticeably faster than printing each iteration for large amounts of words.

Upvotes: 2

gilch
gilch

Reputation: 11681

You can import Python 3's print_function in Python 2.7 by using a future import.

from __future__ import print_function

The future imports must be at the top to work.

Then you can use the end and sep keyword arguments like in Python 3. This lets you change the print ending from the default "\n" to something else, like "".

print(new_sent, end="")

Upvotes: 0

gilch
gilch

Reputation: 11681

If you add a , at the end of your print statement, it will not print out the ending newline.

print new_sent,

Upvotes: 0

Related Questions