给定一个列表(可能不止一个),我想在列表中用空格分隔一行。最好的方法是什么?
例如,
输入:
sentence1=["I", "like", "yellow", "flowers"]
sentence2=["I", "like", "blue", "sky"]
输出:
I like yellow flowers
I like blue sky
答案 0 :(得分:2)
你走了:))
print(' '.join(sentence1))
print(' '.join(sentence2))
join()是一个字符串方法,它返回一个与iterable元素连接的字符串。语法:
string.join(iterable)
答案 1 :(得分:2)
这将输出句子,每个句子都在各自的行上
print(" ".join(sentence1))
print(" ".join(sentence2))
请务必修复列表定义中的语法错误。
答案 2 :(得分:1)
使用*
sentence1=["I", "like", "yellow", "flowers"]
sentence2=["I", "like", "blue", "sky"]
print(*sentence1)
print(*sentence2)
答案 3 :(得分:0)
此功能可以帮助您:
def join(*args):
result = list()
for i in args:
result.extend(i)
return ' '.join(result)
sentence1=["I", "like", "yellow", "flowers"]
sentence2=["I", "like", "blue", "sky"]
sentence3=["I", "like", "green", "grass"]
join(sentence1, sentence2, sentence3)
答案 4 :(得分:0)
在Python3中,您可以使用
print(*mylist)
在Python 2中
for i in range(len(mylist)):
print mylist[i],