r=[]
x='hi'
y='there'
z='how are you?'
for i in range(4):
r.append(x)
r.append(y)
r.append('\n')
r.append(z)
print(r)
当前结果:
['hi', 'there', '\n', 'how are you ?', 'hi', 'there', '\n', 'how are you ?', 'hi', 'there', '\n', 'how are you ?', 'hi', 'there', '\n', 'how are you ?']
它不会换行。有人可以帮我这个简单的程序吗?
预期输出:
hi there
how are you?
hi there
how are you?
...
答案 0 :(得分:0)
您需要在循环末尾附加另一个换行符,并使用join方法打印结果
r=[]
x='hi'
y='there'
z='how are you?'
for i in range(4):
r.append(x)
r.append(y)
r.append('\n')
r.append(z)
r.append('\n')
print(r)
print(" ".join(r))
嗨,在那里
你好吗?
嗨
你好吗?
嗨
你好吗?
嗨
你好吗?
答案 1 :(得分:0)
您应该将字符串连接到输出字符串,而不是附加到列表:
output = ''
x = 'hi'
y = 'there'
z = 'how are you?'
for i in range(4):
output += x + ' ' + y + '\n' + z + '\n'
print(output)
给出:
hi there
how are you?
hi there
how are you?
hi there
how are you?
hi there
how are you?