Python 3.8中print输出格式问题:如何让World与最后一行Hello同行
Got it, let's sort this out! The problem with your current code is that 'Hello\n'*5 adds a newline after every single "Hello"—including the fifth one. That's why "World" ends up sitting on a brand new line instead of next to the last "Hello".
Here are a few simple, Pythonic ways to fix this in Python 3.8:
Slice off the trailing newline
Since'Hello\n'*5ends with an extra newline character, you can use string slicing to trim that off before printing:print('Hello\n'*5[:-1], end=' World')The
[:-1]syntax grabs everything in the string except the last character (which is the unwanted newline), so the fifth "Hello" is ready to have "World" join it on the same line.Use
str.join()for cleaner string constructionjoin()is perfect here because it only inserts separators between elements, not at the end of the whole string:print('\n'.join(['Hello'] * 5), end=' World')This builds a string that's
Hello\nHello\nHello\nHello\nHello(no trailing newline), then appends " World" right after the final "Hello".Unpack a list with
print()'ssepparameter
You can pass each "Hello" as a separate argument toprint(), usesepto handle the newlines, and then add "World" viaend:print(*['Hello'] * 5, sep='\n', end=' World')The
*unpacks the list into individual "Hello" arguments,sep='\n'puts a newline between each one, andend=' World'tacks your desired text onto the final line.
All of these solutions will produce the output you're looking for:
Hello
Hello
Hello
Hello
Hello World
内容的提问来源于stack exchange,提问作者Kaushal Vyas

