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

return string without punctuation

I’m a beginner who’d like to return strings in pairs of characters. If the input to the function is odd then the last pair it to include an _.

Example: solution("asdfadb") should return ['as', 'df', 'ad', 'b_']

My code however, returns: ['a', 's']['d', 'f']['a', 'd']['b', '_']

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

I’ve tried multiple ways and cannot get it to return the correctly formatted result:

def solution(s):
    if len(s)%2 != 0:
        s = "".join((s, "_"))
    s = list(s)
    s = [ s[i:i+2] for i in range(0 , len(s) , 2) ]
    s = ''.join(str(pair) for pair in s )
    print(s)

solution("asdfadb")
['a', 's']['d', 'f']['a', 'd']['b', '_']

>Solution :

You had a small confusion in the last list comprehension, try this (see my comment):

def solution(s):
    if len(s)%2 != 0:
        s = "".join((s, "_"))
    s = list(s)
    s = [ s[i:i+2] for i in range(0 , len(s) , 2) ]
    s = [''.join(pair) for pair in s] # For each sublist (aka pair) - do join.
    print(s)

Output:

['as', 'df', 'ad', 'b_']
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