Answer a question

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?

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]))
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐