英文:
If the string contains an odd number of characters, 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("")) # []
英文:
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("")) # []
答案1
得分: 1
只需向临时副本添加一个字符,然后使用该字符进行操作:
def split_string(string: str) -> list:
s = string + "_" # <----
list1 = 展开收缩 for i in range(0, len(string), 2)]
# ^
return list1
英文:
Just add a character to a temporary copy, and work with that:
def split_string(string: str) -> list:
s = string + "_" # <----
list1 = 展开收缩 for i in range(0, len(string), 2)]
# ^
return list1
答案2
得分: 1
itertools
模块提供了 grouper
函数的定义:
from itertools import zip_longest
def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
"将数据收集到非重叠的固定长度块中"
# 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')
你的函数是一个特殊情况:它将字符串分割成长度为2的组,使用“_”填充不完整的块,并将结果的2元组连接成单个字符串。
def split_string(s):
return list(map(''.join, grouper(s, 2, fillvalue="_")))
# return [''.join(t) for t in grouper(s, 2, fillvalue="_")]
英文:
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="_")]
答案3
得分: 1
你可以在返回列表之前调整最后一个元素:
if len(string) % 2:
list1[-1] += "_"
或者支持其他值的 n
:
if add := -len(string) % n:
list1[-1] += "_" * add
或者,使用迭代器:
def split_string(string: str) -> list:
it = iter(string)
return [c + next(it, "_") for c in it]
英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论