split python strings into pairs & complete uneven pairs 1

split python strings into pairs & complete uneven pairs

>>> s = "abcde"
>>> k = 2
>>> [s[i:i+k].ljust(k, "_") for i in range(0, len(s), k)]
['ab', 'cd', 'e_']

Here is what the above code is Doing:
1. s[i:i+k] is the substring of length k starting at index i.
2. .ljust(k, “_”) pads the substring with “_” to make it length k.
3. range(0, len(s), k) is a list of the starting indices of the substrings.

Similar Posts