简体   繁体   中英

Split string by list of indexes

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?

You need to start from the 0 th 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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