Python 🐍 challenge_27⚔️
Mahmoud EL-kariouny

Mahmoud EL-kariouny @mahmoudessam

About: Software🌟developer👨‍💻

Location:
Egypt/Alex
Joined:
Jun 21, 2020

Python 🐍 challenge_27⚔️

Publish Date: Apr 22 '23
1 1

Split Strings

  • Complete the solution so that it splits the string Into pairs of two characters.
  • If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').

Examples:

solution('abc')  should return => ['ab', 'c_']
solution('abcdef') should return => ['ab', 'cd', 'ef']
Enter fullscreen mode Exit fullscreen mode
Task URL: Link

My Solution:

def solution(s):
    step = 2
    if len(s) % 2 == 0:
        return  [s[index : index + step] for index in range(0, len(s), step)]
    else:
        odd_str = [s[index : index + step] for index in range(0, len(s), step)] 
        el = odd_str[-1] + '_'
        odd_str.pop()
        odd_str.append(el)
        return odd_str

Enter fullscreen mode Exit fullscreen mode

Code Snapshot:

Image description

Learn Python

Python top free courses from Coursera🐍💯🚀

🎥

Connect with Me 😊

🔗 Links

linkedin

twitter

Comments 1 total

  • Leonardo Bispo
    Leonardo BispoJun 25, 2023

    just adding "_" to the original string gives you chance to use only one behavior

    def solution(s):
        if len(s) % 2 != 0:
            s = s + '_'
        return  [s[index : index + 2 ] for index in range(0, len(s), step)]
    
    Enter fullscreen mode Exit fullscreen mode

    creating a step variable is just needed if you want to change it somethimes, but it could require some changes to be implemented because the number of underscores depends on the rest of the division.

Add comment