python字符串将slice和拆分为一个列表

2024-05-23 22:33:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,例如“streemlocalbbv”

我有我的_函数,它接受这个字符串和我想在原始字符串中找到的字符串(“loc”)。我想要得到的回报是这个

my_function("streemlocalbbv", "loc")

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

到目前为止我所做的是

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]

尝试在原始字符串中查找我要查找的字符串的索引,然后拆分原始字符串。但是从这里我不知道我该怎么做


Tags: 函数字符串outputstringindexlenmyfunction
3条回答

使用split, index and insert函数来解决此问题

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

您可以使用str.partition,它完全满足您的需要:

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

使用split函数:

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

相关问题 更多 >