Search code examples
pythonstringsplitchar

If the string contains an odd number of characters, how to add a ( _ ) character after the last character


How to add a character(_) after the last character?

def split_string(string: str) -> list:
    n = 2
    list1 = [string[i: i + n] for i in range(0, len(string), n)]
    return list1


print(split_string("123456"))  # ["12", "34", "56"]
print(split_string("ab cd ef"))  # ["ab", " c", "d ", "ef"]
print(split_string("abc"))  # ["ab", "c_"]
print(split_string(" "))  # [" _"]
print(split_string(""))  # []

Solution

  • You could just adjust the last element before you return the list:

       if len(string) % 2:
            list1[-1] += "_"
    

    Or to support other values of n:

        if add := -len(string) % n:
            list1[-1] += "_" * add
    

    Alternatively, with an iterator:

    def split_string(string: str) -> list:
        it = iter(string)
        return [c + next(it, "_") for c in it]