Question 3 (8 marks): Write a program that takes a string from the user and splits it into a list using a space (" ") as the delimiter. Do not use split(). Print the result. Hints: Use a for loop to loop through the string. Keep track of the index of the last part of the string that you "split". When you reach a space, you know to split again. Use string slicing to get the portion of the string that you want.

Respuesta :

Answer:

In Python:

mystr = input("Sentence: ")

mylist = []

word = ""

for i in range(len(mystr)):

   if not i == len(mystr)-1:

       if not mystr[i] == " ":

           word+=mystr[i]

       else:

           mylist.append(word)

           word = ""

   else:

       word+=mystr[i]

       mylist.append(word)

print(mylist)

Explanation:

Prompt the user for an input sentence

mystr = input("Sentence: ")

Initialize an empty list

mylist = []

Initialize each word to an empty string

word = ""

Iterates through the input sentence

for i in range(len(mystr)):

If index is not the last, the following if condition is executed

   if not i == len(mystr)-1:

If the current character is not space

       if not mystr[i] == " ":

Append the character to word

           word+=mystr[i]

If otherwise

       else:

Append word to the list

           mylist.append(word)

Set word to an empty string

           word = ""

If otherwise; i.e. If index is not the last

   else:

Append the last character to word

       word+=mystr[i]

Append word to the list

       mylist.append(word)

Print the list

print(mylist)

ACCESS MORE