Home > Back-end >  Split string by list of indexes
Split string by list of indexes

Time:11-26

I need a function that splits the string by indexes specified in indexes. Wrong indexes must be ignored. My code:

def split_by_index(s: str, indexes: List[int]) -> List[str]:
    parts = [s[i:j] for i,j in zip(indexes, indexes[1:] [None])]
    return parts

My strings:

split_by_index("pythoniscool,isn'tit?", [6, 8, 12, 13, 18])
split_by_index("no luck", [42])

Output:

['is', 'cool', ',', "isn't", 'it?']
['']

Expected output:

["python", "is", "cool", ",", "isn't", "it?"]
["no luck"]

Where is my mistake?

CodePudding user response:

You need to start from the 0th index, while you are starting from 6:8 in your first example and 42:None in the second:

def split_by_index(s: str, indexes: List[int]) -> List[str]:
    parts = [s[i:j] for i,j in zip([0]   indexes, indexes   [None])]
    return parts

CodePudding user response:

the only appending zero to your list would have solved as mentioned in my comment, but for ignoring if the index is bigger you could add the same condition inside for loop

def split_by_index(s: str, indexes):
    indexes = [0]   indexes   [None]
    parts = [s[i:j] for i,j in zip(indexes, indexes[1:]) if j and j < len(s)]
    return parts

CodePudding user response:

The only way I found that works for both cases:

def split_by_index(s: str, indexes: List[int]) -> List[str]:
    parts = [s[i:j] for i,j in zip([0]   indexes, indexes   [None])]
    if '' in parts:
        parts.pop()
    return parts
  • Related