DEV Community

Cover image for Code Wars - 6kyu 'Split Strings' solution in Python
claudiogiubrone
claudiogiubrone

Posted on

Code Wars - 6kyu 'Split Strings' solution in Python

Hello wonderful people,

As a beginner programmer, I've started putting into practice what I'm learning by solving problems on platforms like Codewars.

To help myself while studying, I thought of documenting my mental process toward the solutions. Later, I realized that sharing my experiences and the approaches I take to these problems could be useful for others on their own learning journey.

This guide provides a detailed breakdown of the thought process and implementation for solving the Code Wars kata "Split Strings" (level 6kyu) coding challenge.

It is designed to help new programmers understand how to approach and solve a common problem, focusing on logical steps and robust code.


The Problem

The task is to write a function that takes a string and splits it into a list of two-character pairs. If the string contains an odd number of characters, the final pair must be completed by adding an underscore (_).

  • Example 1: The string 'abc' should be transformed into ['ab', 'c_'].
  • Example 2: The string 'abcdef' should become ['ab', 'cd', 'ef'].

Step 1: Handling the Edge Case (Odd-Length Strings)

The most important requirement is handling strings with an odd number of characters. A simple check at the beginning of the function can solve this. The modulo operator (%) is perfect for this, as it returns the remainder of a division. If the length of the string divided by 2 has a remainder of 1 (len(s) % 2 != 0), the string's length is odd. In this case, an underscore should be appended to the string. This ensures that the main logic of the function can always work with an even-length string.

Step 2: Iterating and Slicing the String

The core of the solution requires processing the string in chunks of two characters. A for loop is ideal for this. The range() function can be used with a third argument, step, to control the loop's increment. By setting the step to 2, the loop's index i will jump from 0 to 2 to 4 and so on, allowing us to capture two characters at a time.

Within the loop, string slicing s[i:i+2] is used. This operation returns a substring starting from index i up to (but not including) index i+2, effectively grabbing a two-character pair.

Step 3: Storing the Results

As each pair is generated, it needs to be stored in a collection. A list is the perfect data structure for this task. The process is straightforward:

  1. Initialize an empty list before the loop.
  2. Use the .append() method to add each two-character slice to the list during each iteration of the loop.
  3. After the loop completes, the function should return the final list.

The Final Code

Combining all the steps above results in a concise and robust function. The code is designed to be self-contained and ready for use in a test environment, where the platform handles providing the input to the function directly.

def solution(s):
    """
    Splits a string into a list of character pairs.
    If the string has an odd number of characters, the last pair is padded with an underscore.
    """
    ls = []
    # Step 1: Handle odd-length strings by appending an underscore.
    if len(s) % 2 != 0:
        s += '_'

    # Step 2: Loop through the string in steps of 2.
    for i in range(0, len(s), 2):
        # Step 3: Slice and append each pair to the list.
        ls.append(s[i:i+2])

    return ls
Enter fullscreen mode Exit fullscreen mode

Conclusion

I have also create a repo on github.
You can see if it can help you at this link.

Top comments (0)