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

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 :

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

Just add a character to a temporary copy, and work with that:

def split_string(string: str) -> list:
    s = string + "_"   # <----
    list1 = [s[i: i + 2] for i in range(0, len(string), 2)]
    #        ^
    return list1
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