根据特定要求重新排列字符串以返回字符串列表

时间:2017-10-18 14:52:21

标签: python list

您好,所以我希望用def,find等简单的东西构建这个python函数。到目前为止,我知道如何获取代码的第一部分。

给定"HELLODOGMEMEPAPA"这样的字符串,我需要返回一个给我三件事的列表:

  • 我将表示为before_dog

  • 之前的所有内容
  • 单词dog和后面的三个字母表示为dog_3letters

  • dog_3letters之后的所有内容,我将其称为everything_after

列表的格式为[before_dog,dog_3letters,everything_after]

因此,如果给出"HELLODOGMEMEPAPA"这样的字符串,我需要返回列表["HELLO", "DOGMEM", "EPAPA"]或类似"HEYWHATDOGDODOD"的字符串,我需要返回["HEYWHAT","DOGDOD","OD"]

这是我到目前为止所做的:

def split_list(words):
    # declare the list
    lst = []
    # find the first position
    first_pos=words.find("DOG")
    # find the first_pos
    first = words [0:first_pos]
    lst.append(first)
    return lst

3 个答案:

答案 0 :(得分:1)

使用切片查找预期的子字符串,如下所示:

def split_word(s, word):
    i = s.find(word)
    n = len(word)
    before = s[:i]
    word3  = s[i:i+n+3]
    after  = s[i+n+3:]
    return [before, word3, after]

例如:

split_word('HELLODOGMEMEPAPA', 'DOG')
=> ['HELLO', 'DOGMEM', 'EPAPA']
split_word('HEYWHATDOGDODOD', 'DOG')
=> ['HEYWHAT', 'DOGDOD', 'OD']

答案 1 :(得分:0)

只需使用find获取DOG的位置,然后:

>>> s
=> 'HELLODOGMEMEPAPA'

>>> pos_dog = s.lower().find('DOG')
>>> pos_dog
=> 5

>>> before_dog = s[:pos_dog]
>>> before_dog
=> 'HELLO'

>>> dog_3letters = s[pos_dog : pos_dog+6]
>>> dog_3letters
=> 'DOGMEM'

>>> everything_after = s[pos_dog+6 : ]
>>> everything_after
=> 'EPAPA'

>>> [before_dog, dog_3letters, everything_after]
=> ['HELLO', 'DOGMEM', 'EPAPA']

答案 2 :(得分:0)

似乎明显使用正则表达式,请参阅下面的示例代码

>>> import re
>>> teststr="HEYWHATDOGDODOD"
>>> x=re.search('(.*)(DOG...)(.*)',teststr)
>>> x.groups()
('HEYWHAT', 'DOGDOD', 'OD')