Search code examples
pythonpython-3.xpython-dateutil

Python3: Use Dateutil to make multiple vars from a long string


I have a program where I would like to randomly pull a line from a song, and string them together with other lines from other songs. Looking into I saw that the dateutil library might be able to help me parse multiple variables from a string, but it doesn't do quite what I want.

I have multiple strings like this, only much longer.

"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..."

I want to randomly pull one line from this string (To the page break) and save it as a variable but iterate this over multiple strings, any help would be much appreciated.


Solution

  • assuming you want to pull one line at random from the string you can use choice from the random module.

    random. choice ( seq ): Return a random element from the non-empty sequence seq. If seq is empty, raises 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)
    

    OUTPUT

    That shape is my shade