Home > OS >  Unite two last items in the end of list, without commas (Python)
Unite two last items in the end of list, without commas (Python)

Time:07-31

This code splits a string every two items, separated by commas and if the quantity of all items is odd items it need to add "" symbol to the last (odd) item in the list.

def split_string(string: str) -> list:

    result = []
    for char in range(0, len(string), 2):
        result.append(string[char: char   2])

    if len(string) % 2 != 0:
         result.append("_") 
        
    return result


split_string("abcde")

Code returns ["ab", "cd", "e", ""] but I need ["ab", "cd", "e"], i.e. "e_" without a comma between the last two items "e" and "". So I need code to return ["ab", "cd", "e"] i.e underscore after "e" without space and comma as a symbol of an absent second item. Please help to get the result

CodePudding user response:

The code returns ["ab", "cd", "e", "_"], not ["ab", "cd", "e", ""]. You should use result[-1] = "_" in the if statement. Your current code appends to the list, while result[-1] appends to the last element of the list (you can not use append() on strings, hence the = concatenation operator).

I recommend changing the condition in the if statement as well, this would be easier to understand later: if len(result[-1]) != 2:.

  • Related