If the string contains an odd number of characters, how to add a ( _ ) character after the last character
Question:
How to add a character(_) after the last character?
def split_string(string: str) -> list:
n = 2
list1 = [string[i: i + n] for i in range(0, len(string), n)]
return list1
print(split_string("123456")) # ["12", "34", "56"]
print(split_string("ab cd ef")) # ["ab", " c", "d ", "ef"]
print(split_string("abc")) # ["ab", "c_"]
print(split_string(" ")) # [" _"]
print(split_string("")) # []
Answers:
Just add a character to a temporary copy, and work with that:
def split_string(string: str) -> list:
s = string + "_" # <----
list1 = [s[i: i + 2] for i in range(0, len(string), 2)]
# ^
return list1
The itertools
module provides the definition of a function grouper
:
from itertools import zip_longest
def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
"Collect data into non-overlapping fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
args = [iter(iterable)] * n
if incomplete == 'fill':
return zip_longest(*args, fillvalue=fillvalue)
if incomplete == 'strict':
return zip(*args, strict=True)
if incomplete == 'ignore':
return zip(*args)
else:
raise ValueError('Expected fill, strict, or ignore')
Your function is a special case: you split your string into groups of 2, padding incomplete chunks with "_"
, and joining the resulting 2-tuples back into a single string.
def split_string(s):
return list(map(''.join, grouper(s, 2, fillvalue="_")))
# return [''.join(t) for t in grouper(s, 2, fillvalue="_")]
You could just adjust the last element before you return the list:
if len(string) % 2:
list1[-1] += "_"
Or to support other values of n
:
if add := -len(string) % n:
list1[-1] += "_" * add
Alternatively, with an iterator:
def split_string(string: str) -> list:
it = iter(string)
return [c + next(it, "_") for c in it]
How to add a character(_) after the last character?
def split_string(string: str) -> list:
n = 2
list1 = [string[i: i + n] for i in range(0, len(string), n)]
return list1
print(split_string("123456")) # ["12", "34", "56"]
print(split_string("ab cd ef")) # ["ab", " c", "d ", "ef"]
print(split_string("abc")) # ["ab", "c_"]
print(split_string(" ")) # [" _"]
print(split_string("")) # []
Just add a character to a temporary copy, and work with that:
def split_string(string: str) -> list:
s = string + "_" # <----
list1 = [s[i: i + 2] for i in range(0, len(string), 2)]
# ^
return list1
The itertools
module provides the definition of a function grouper
:
from itertools import zip_longest
def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
"Collect data into non-overlapping fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
args = [iter(iterable)] * n
if incomplete == 'fill':
return zip_longest(*args, fillvalue=fillvalue)
if incomplete == 'strict':
return zip(*args, strict=True)
if incomplete == 'ignore':
return zip(*args)
else:
raise ValueError('Expected fill, strict, or ignore')
Your function is a special case: you split your string into groups of 2, padding incomplete chunks with "_"
, and joining the resulting 2-tuples back into a single string.
def split_string(s):
return list(map(''.join, grouper(s, 2, fillvalue="_")))
# return [''.join(t) for t in grouper(s, 2, fillvalue="_")]
You could just adjust the last element before you return the list:
if len(string) % 2:
list1[-1] += "_"
Or to support other values of n
:
if add := -len(string) % n:
list1[-1] += "_" * add
Alternatively, with an iterator:
def split_string(string: str) -> list:
it = iter(string)
return [c + next(it, "_") for c in it]