python string split slice and into a list

Viewed 249

I have a string for example "streemlocalbbv"

and I have my_function that takes this string and a string that I want to find ("loc") in the original string. And what I want to get returned is this;

my_function("streemlocalbbv", "loc")

output = ["streem","loc","albbv"]

what I did so far is

def find_split(string,find_word):

    length = len(string)
    find_word_start_index = string.find(find_word)
    find_word_end_index = find_word_start_index + len(find_word)

    string[find_word_start_index:find_word_end_index]

    a = string[0:find_word_start_index]
    b = string[find_word_start_index:find_word_end_index]
    c = string[find_word_end_index:length]


    return [a,b,c]

Trying to find the index of the string I am looking for in the original string, and then split the original string. But from here I am not sure how should I do it.

3 Answers

You can use str.partition which does exactly what you want:

>>> "streemlocalbbv".partition("loc")
('streem', 'loc', 'albbv')

Use the split function:

def find_split(string,find_word):
    ends = string.split(find_word)
    return [ends[0], find_word, ends[1]]

Use the split, index and insert function to solve this

def my_function(word,split_by):
  l = word.split(split_by)
  l.insert(l.index(word[:word.find(split_by)])+1,split_by)
  return l
print(my_function("streemlocalbbv", "loc"))
#['str', 'eem', 'localbbv']
Related