DEV Community

Cover image for Python ๐Ÿ challenge_27โš”๏ธ
Mahmoud EL-kariouny
Mahmoud EL-kariouny

Posted on

1

Python ๐Ÿ challenge_27โš”๏ธ

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
leonardobispo profile image

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.

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay