pythonstringlist-comprehension

How to take a string and make a list of strings where each string builds up to the original string?


I'm looking to take a string and create a list of strings that build up the original string.

e.g.:

"asdf" => ["a", "as", "asd", "asdf"]

I'm sure there's a "pythonic" way to do it; I think I'm just losing my mind. What's the best way to get this done?


Solution

  • One possibility:

    >>> st = 'asdf'
    >>> [st[:n+1] for n in range(len(st))]
    ['a', 'as', 'asd', 'asdf']