Split Strings - codewars
My approach to solving 'Split Strings' on codewars

This problem is currently rated as a 6 kyu (ratings on codewars range from 8 (easiest) to 1 (hardest)) problem on codewars, this is it’s description :
"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 ('_')."
Before solving thoughts :
Reading that, my thought process going into the problem was “I can use regex to split every 2 characters, then iterate through its output to add in an underscore if the substring only contains 1 character.” (regex stands for regular expressions which are used for searching through text)
My python solution :
solution = lambda s: __import__('re').findall("..",s + "_")
We start by defining a lambda function named 'solution' so codewars can get our answer. Inside, we import re to use regex, and then we use re.findall (re’s findall function is used for finding all matching occurrences of a pattern and returning them in a list.) If the string is empty, we will return an empty list. Next, we get the output of re.findall, which is returning a list that contains the input string split into pairs. It achieves this by using “..” (. in regex stands for matching any character) as our pattern, which will make it only add in increments of 2 characters. We append an underscore to the input string because if the string’s length is uneven, it’ll be by itself, therefore not matching our pattern. I used import to import re so it saves on space.
After thoughts :
This solution was quite short, but can teach you a lesson on not over complicating things. If you ever get stuck with a lengthy solution, think to yourself “Do I really have to write this much code?” If not, then start breaking each line into something more compressed. Compression does not always mean better readability though.
For example, this code (147 bytes):
def counter(start: int, end: int) -> str:
output: str = ""
for x in range(start,end):
output += str(x) + "\n"
return output.rstrip()
is more readable than this code (67 bytes):
counter = lambda s, e: ''.join(f"{x}\n" for x in range(s,e))[:-1]
You may want to use less characters if you need to have a smaller file size, however, if that’s a constraint you probably wouldn’t be using python unless it’s micropython used for microcontrollers.
In conclusion, this was how I solved ‘Split Strings’ on codewars. Hopefully you improve!
— 0xsweat 7/12/2024
My socials :




