Python: for loop - print on the same line
Solution 1
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]))
Solution 2
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.
Solution 3
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:
$
SomeOne
Updated on July 09, 2022Comments
-
SomeOne almost 2 years
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
? -
thefourtheye over 10 yearsI always had this doubt, can we use
iter
to stop when any of the items in a list is encountered? -
Ashwini Chaudhary over 10 years@thefourtheye I don't think so, because we don't have access to
item
insideiter
, but we can useitertools.takewhile
for that. -
thefourtheye over 10 years@hcwhsa You mean we can combine
iter
andtakewhile
to do that? -
thefourtheye over 10 yearsDownvoter, could you please explain why?
-
Ashwini Chaudhary over 10 years@thefourtheye No, just
takewhile
:for x in takewhile(lambda x: x not in my_list, (x() for x in repeat(f)))
, wheref
isf = partial(input, 'Enter a sentence: ')
-
wjandrea about 4 yearsNote this only works in Python 2, and OP seems to be using Python 3