Nick
Nick

Reputation: 33

Making a list of separate words with spaces in between from a string input

I need to take an input of a string: "The weather today is" and get an output of ["The","The weather", "The weather today", "The weather today is"]. While I've tried the following, I'm still having trouble with for loops and would really appreciate any help.

My steps are split the string into a list. Then use a for loop to insert the words in the i, i+1... order until it reaches the end of the range.


def test(data):
    splitString = data.split()
    result = {}

    for i in range(len(splitString)):
        if i != max(range(len(splitString))):
            result.append(i)
            i + 1
    return result


s = "The weather today is"
print(test(s))

input: "The weather today is" output: ["The","The weather", "The weather today", "The weather today is"]

Upvotes: 0

Views: 52

Answers (3)

Christopher Krause
Christopher Krause

Reputation: 114

You could join the splitted results like this:

def test(data):
    splitted = data.split()
    return [
        ' '.join(splitted[:i])
        for i in range(1, len(splitted) + 1)
    ]

test('The weather today is')
# ['The', 'The weather', 'The weather today', 'The weather today is']

Alternative solution without split and join:

def test(data):
    def iter_values():
        for idx, character in enumerate(data):
            if character == ' ':
                yield data[:idx]
        yield data
    return list(iter_values())

test('The weather today is')
# ['The', 'The weather', 'The weather today', 'The weather today is']

Upvotes: 0

DarrylG
DarrylG

Reputation: 17166

def test(data):
  # Form words
  words = data.split()

  # Use list comprehension to generate
  # words[:i] are sub list of words from zero to index i
  # we join this sublist into a string
  return [" ".join(words[:i]) for i in range(1, len(words)+1)]

t = "The weather today is"
print(test(t)) # ['The', 'The weather', 'The weather today', 'The weather today is']

Upvotes: 0

scarecrow
scarecrow

Reputation: 6874

You iterate over the list of strings one by one. At every item you reach, include the previous items till the current position using the slice operator [:] which will give you the substring you expect. Refer to the below snippet:

a = ["the", "weather", "today", "is", "bad"]
for i in range(len(a)):
   print(a[:i])  # slice till the current element

[]
['the']
['the', 'weather']
['the', 'weather', 'today']
['the', 'weather', 'today', 'is']

Upvotes: 1

Related Questions