Python: for a loop - print on the same line

I have a question about printing on the same line using a for loop in Python 3. I was looking for an answer, but I could not find any relevant one.

So, I have something like this:

 def function(variable): some code here return result 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 the user enters a "short sentence" into the sentence, the function must do something with it and it should be printed on the same line. Say the function adds 't' to the end of each word, so the output should be

In shortt sentencet

However, at the moment, the output is:

IN
Shortt
sentencet

How can I print the result on the same line? Or should I create a new line so that

 new_string = '' new_string = new_string + new_item 

and it repeats, and in the end do I type new_string?

+8
python string
source share
3 answers

Use the 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])) 
+18
source share

The easiest solution is to use a comma in your print statement:

 for i in range(5): print i, #prints 1 2 3 4 5 

Note that there is no trailing newline; print without arguments after adding a loop.

+8
source share

Since 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 

Better yet, use 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: abc at bt ct Enter a sentence: $ 
+2
source share

All Articles