将单词分为两对,但变化不大

问题描述

在给定任务上我需要帮助-

将字符串分成两个字符对。如果字符串中包含奇数个字符,则最后一对中缺少的第二个字符应替换为下划线('_')。

def split_pairs(a):
    if len(a)%2==0:
        a.split(',',2)
    else:
        a.split(',2)
        a.replace(items[2][-1],'_')
        return a

解决方法

您假设使用特定的分隔符。无需进行此假设,您可以遍历起始索引(以2为步长),并提取相关子字符串。如果需要,将_连接到最后一个:

def split_pairs(a):
    out = [a[i:i+2] for i in range(0,len(a),2)]
    if len(out[-1]) == 1:
        out[-1] += '_'
    return out

print(split_pairs('Hello'),split_pairs('world!'))

这给出了:

['He','ll','o_'] ['wo','rl','d!']

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...