62.6k views
3 votes
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.

User Ulas Keles
by
7.8k points

1 Answer

3 votes

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)

Step-by-step 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)

User Msporek
by
7.6k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.