简体   繁体   English

python 字符串拆分切片并放入列表

[英]python string split slice and into a list

I have a string for example "streemlocalbbv"我有一个字符串,例如“streemlocalbbv”

and I have my_function that takes this string and a string that I want to find ("loc") in the original string.我有 my_function 接受这个字符串和我想在原始字符串中找到的字符串(“loc”)。 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.但是从这里我不确定我应该怎么做。

You can use str.partition which does exactly what you want:您可以使用str.partition完全符合您的要求:

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

Use the split function:使用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使用split, index and insert function 来解决这个问题

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM