【问题标题】:Python3: Use Dateutil to make multiple vars from a long stringPython3:使用 Dateutil 从长字符串中创建多个变量
【发布时间】:2019-12-09 13:31:49
【问题描述】:

我有一个程序,我想从一首歌曲中随机抽取一条线,并将它们与其他歌曲中的其他线串在一起。调查后我发现 dateutil 库可能能够帮助我从字符串中解析多个变量,但它并不能完全满足我的要求。

我有多个这样的字符串,只有更长的时间。

"This is the day\nOf the expanding man\nThat shape is my shade\nThere where I used to stand\nIt seems like only yesterday\nI gazed through the glass\n..."

我想从这个字符串中随机拉出一行(到分页符)并将其保存为变量,但在多个字符串上迭代,任何帮助将不胜感激。

【问题讨论】:

  • 所以你想从一串行中随机抽取一行?
  • 一次需要多个变量,还是只需要该连接字符串中的随机行..?
  • 您在问这个问题的哪个方面?您已经解决了哪些方面(如果有的话)?

标签: python python-3.x python-dateutil


【解决方案1】:

假设您想从字符串中随机抽取一行,您可以使用random 模块中的choice。

随机。选择(seq):从非空中返回一个随机元素 序列如果 seq 为空,则引发 IndexError。

from random import choice
data = "This is the day\nOf the expanding man\nThat shape is my shade\nThere where I used to stand\nIt seems like only yesterday\nI gazed through the glass\n..."
my_lines = data.splitlines()
my_line = choice(my_lines)
print(my_line)

输出

That shape is my shade

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多