我需要在代码中添加一个空格和换行符



我正在处理一个家庭作业问题,我不知道如何添加空格和换行符。我尝试了很多改变。

问题:

编写一个循环以打印hourly_temperature中的所有元素。用->分隔元素;被空间包围。

给定程序的样本输出:

输入:

90 92 94 95

输出:

90 -> 92 -> 94 -> 95 

注意:95后面跟着一个空格,然后是一个换行符。换行符应该只包括在所有项目之后的一次。

以下是我解决问题的尝试:

user_input = input()
hourly_temperature = user_input.split()
for item in hourly_temperature:
if item != hourly_temperature[len(hourly_temperature)-1]:
print(item, end = " -> ")

我不确定我是否理解这个问题。95指的是什么?

在python中打印新行打印'\n',它将打印新行,打印空格使用文字空间

>>> print("This ends with a space then a newline n")
This ends with a space then a newline 
>>> print("This will show up nas two lines")
This will show up 
as two lines
>>> 

我认为您有几个问题,从您的输入开始:

>>> user_input = input()
90 92 94 95
>>> user_input
'90 92 94 95'
>>> user_input.split()
['90', '92', '94', '95']

这实际上并不包含换行符,但即使是,您也可以像这样快速删除它:

hourly_temperature = user_input.split()[:-1]

最后,如果使用join打印,可能最简单:

print(" -> ".join(hourly_temperature))

CCD_ 2是所有字符串上的一个方法;使用原始字符串将此数组中的每个项粘在一起"因此,用逗号将数字粘合在一起的一种快速方法是:", ".join([1,2,3])

可能是你的指示说你需要在末尾包含一个空格和换行符——这还不清楚,但input()调用本身不会包含这一点。

如果你需要在末尾添加一些东西,另一种方法是使用f-string:

printable_output = "{} n".format(" -> ".join(hourly_temperature))
print(printable_output)

这导致:

>>> user_input = input()
90 92 94 95
>>> hourly_temperature = user_input.split()[:-1]
>>> printable_output = "{} n".format(" -> ".join(hourly_temperature))
>>> print(printable_output)
90 -> 92 -> 94 
>>>

(请注意,最后一个元素被删除了,因为我正在删除我拆分user_input的行上的最后一个元件。我认为没有必要这样做——如果不这样做的话,只删除[:-1]。(

在数组中查找最新数据,如果找到,则打印新行:

if item == item[-1]:
print("n")
print(item, end = " -> ")
else:
print(item, end = " -> ")

最新更新