我想从一个更大的名字列表中创建一个随机的名单。问题是,生成的名称之间没有空格。我无法理解如何放置空间。这是我的代码
import random
final_list = ""
a=0
sss = ("John","Adam","Sara","Lory","Dick","Popeye")
while a<7:
x = random.choice(sss)
final_list += x
a += 1
print (final_list)
结果是这样的: SaraAdamDickPopeyeSaraPopeyeLory
如何在名称之间添加空格?此外,任何人都可以建议更短的方式来执行此代码吗?
答案 0 :(得分:0)
您可以在原始连接中添加一个空的空字符串:
x = random.choice(sss)
final_list += " "+x if final_list else x
a += 1
或者更准确地说,在列表理解中使用' '.join
:
sss = ("John","Adam","Sara","Lory","Dick","Popeye")
final_string = ' '.join(random.choice(sss) for i in range(7))
答案 1 :(得分:0)
要避免前导或尾随空格,请检查final_list
的长度是否已大于零。
import random
final_list = ""
a=0
sss = ("John","Adam","Sara","Lory","Dick","Popeye")
while a<7:
x = random.choice(sss)
final_list = final_list + " " + x if len(final_list) > 0 else x
a += 1
print (final_list)
如果您不想进行显式检查,则可以在构造final_list
后使用strip函数删除前导和尾随空格。