是否可以将此打印行分开,以便它打印在单独的行上而不是打印在一行上?

问题描述 投票:0回答:2
your_name = input("Please tell me your name:  ")
your_age = int(input("Please tell me your age:  "))
print_times = int(input("How many times would you like to print this message? "))
years_old = 2023 + 100 - your_age
print(("Hi ", your_name + " ", "you will be 100 years old in ", years_old)  *  print_times)
python printing newline
2个回答
0
投票

而不是

print(("Hi ", your_name + " ", "you will be 100 years old in ", years_old)  *  print_times)

您可以使用更具可读性的 f 字符串与 ' ' 分隔输出:

print(f'Hi, {your_name}, you will be 100 years old in {years_old} \n' * print_times)

0
投票

就像 Joe 所写,你可以将

\n
放在字符串的末尾。我们假设您在几年后想要新的生产线。

print("Hi " + your_name + ", you will be 100 years old in " + str(years_old) + ".\n" *  print_times)

greeting_msg = "Hi " + your_name + ", you will be 100 years old in " + str(years_old)
print_timesprint("\n".join([greeting_msg] * print_times)

就像 Rivka 所写的那样,使用 f 字符串或使用

str.format
方法,字符串格式可能会更清晰。

您也可以多次执行

print

greeting_msg = "Hi " + your_name + ", you will be 100 years old in " + str(years_old)
for _ in range(print_times):
    print(greeting_message)
© www.soinside.com 2019 - 2024. All rights reserved.