Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: for loop - print on the same line [duplicate]

I have a question about printing on the same line using for loop in Python 3. I searched for the answer but I couldn't find any relevant.

So, I have something like this:

def function(s):
    return s + 't'

item = input('Enter a sentence: ')

while item != '':
    split = item.split()
    for word in split:
        new_item = function(word)
        print(new_item)
    item = input('Enter a sentence: ')

When a user types in 'A short sentence', the function should do something with it and it should be printed on the same line. Let's say that function adds 't' to the end of each word, so the output should be

At shortt sentencet

However, at the moment the output is:

At
shortt
sentencet

How can I print the result on the same line easily? Or should I make a new string so

new_string = ''
new_string = new_string + new_item

and it is iterated and at the end I print new_string?

like image 638
SomeOne Avatar asked Nov 17 '13 14:11

SomeOne


3 Answers

Use end parameter in the print function

print(new_item, end=" ")

There is another way to do this, using comprehension and join.

print (" ".join([function(word) for word in split]))
like image 200
thefourtheye Avatar answered Oct 17 '22 20:10

thefourtheye


The simplest solution is using a comma in your print statement:

>>> for i in range(5):
...   print i,
...
0 1 2 3 4

Note that there's no trailing newline; print without arguments after the loop would add it.

like image 38
Mohsin Khazi Avatar answered Oct 17 '22 21:10

Mohsin Khazi


As print is a function in Python3, you can reduce your code to:

while item:
    split = item.split()
    print(*map(function, split), sep=' ')
    item = input('Enter a sentence: ')

Demo:

$ python3 so.py
Enter a sentence: a foo bar
at foot bart

Even better using iter and partial:

from functools import partial
f = partial(input, 'Enter a sentence: ')

for item in iter(f, ''):
    split = item.split()
    print(*map(function, split), sep=' ')

Demo:

$ python3 so.py
Enter a sentence: a foo bar
at foot bart
Enter a sentence: a b c
at bt ct
Enter a sentence: 
$
like image 38
Ashwini Chaudhary Avatar answered Oct 17 '22 21:10

Ashwini Chaudhary