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
?
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]))
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.
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:
$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With