我有一个变量myline,其中我存储了一条带有break的行现在我想打印2个随机行,任何人都可以建议如何做。
import random
myline="This is line 1 \nThis is line 2 \nThis is line 3 \nThis is line 4 \nThis is line 5 "
lines = myline.readlines()
print (random.sample(lines, 2))
答案 0 :(得分:4)
您希望splitlines
代替readlines
:
import random
myline="This is line 1 \nThis is line 2 \nThis is line 3 \nThis is line 4 \nThis is line 5 "
lines = myline.splitlines()
print(random.sample(lines, 2))
# ['This is line 4 ', 'This is line 1 ']
readlines
返回文件中的行列表。在这里,您有一个要拆分的字符串。
如果要打印由换行符分隔的行,只需join
带换行符的行列表:
print('\n'.join(random.sample(lines, 2)))