Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading