Skip to content
Advertisement

How to split a string without using .split()?

I have a function that takes a parameter string and a ‘target’, where the target is a substring of the string. I need to output the index of these substrings within the string. I am not allowed to use the split function, so how else would I split up the string? Ex: if string is “we dont need no education we dont need no thought control no we dont” and the target was “dont” the output would be: [1, 6, 13]

the target could also be ‘we dont’, so I cant split at every space.

I have this, which outputs every character in the string, although I’m not sure why it isn’t outputting just ‘dont’ three times:

#
def position(string, target):
    output = []
    for target in string:
        output.append(target)
    return output

print(position('we dont need no education we dont need no thought control no we dont', 'dont'))
#

I thought about putting the string into a list, but that would not work because it would eliminate being able to use ‘we dont’ as target. So just not sure how to count the instances of the target characters as compared to the characters of the string, and then be able to output the position of the target in the string. Edited for clarification, I hope this helps.

Also pretty sure I am not allowed to use .find()

Advertisement

Answer

Does this fit the requirments ?

example_str = "we dont need no education we dont need no thought control no we dont"
key = "dont"

count = []
word_count = 0

for i in range(len(example_str)):
     if example_str[i] == " ":
        word_count += 1

     if example_str.startswith(key, i):
        count.append(word_count)
        
print(count)

Gives output

[1, 6, 13]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement