【每日一题20220816】拆分字符串

:mage: 完成解决方案,以便将字符串拆分为两个字符对。如果字符串包含奇数个字符,则应将最后一对中缺少的第二个字符替换为下划线 (‘_’) 。

例子:

* 'abc' =>  ['ab', 'c_']
* 'abcdef' => ['ab', 'cd', 'ef']

题目难度:简单
题目来源:https://www.codewars.com/kata/515de9ae9dcfc28eb6000001

def solution(s: str) -> list:
    # your code here

assert solution("asdfadsf") == ['as', 'df', 'ad', 'sf']
assert solution("asdfads") == ['as', 'df', 'ad', 's_']
assert solution("") == []
assert solution("x") == ['x_']
def solution(s: str) -> list:
    # your code here
    if len(s)%2 == 0:
        s = list(s)
        n = len(s)-1
        for i in range(0,n,2):
            s[i] += s[i+1]
        s = s[::2]
        return s
    elif len(s) == 0:
        return []
    else:
        s = s+'_'
        return solution(s)

assert solution("asdfadsf") == ['as', 'df', 'ad', 'sf']
assert solution("asdfads") == ['as', 'df', 'ad', 's_']
assert solution("awsdwerd") == ['aw', 'sd', 'we', 'rd']
assert solution("") == []
assert solution("x") == ['x_']
def solution(s: str) -> list:
    new_s=s+"_"
    return [s[i:i+2]for i in range(0,len(s),2)] if len(s)%2==0 else [new_s[i:i+2]for i in range(0,len(new_s),2)]



assert solution("asdfadsf") == ['as', 'df', 'ad', 'sf']
assert solution("asdfads") == ['as', 'df', 'ad', 's_']
assert solution("") == []
assert solution("x") == ['x_']

def solution(s: str) → list:
r = [s[i:i + 2] for i in range(0, len(s), 2)]
if len(s) % 2 == 1:
r[-1] += “_”
return r

1 个赞
def solution(s: str) -> list:
    # your code here
    list=[]
    i=0
    if len(s) % 2==0:
        while i<len(s):
            list.append(s[i:i+2])
            i=i+2
    else:
        while i<len(s)-1:
            list.append(s[i:i+2])
            i=i+2
        list.append(s[len(s)-1]+'_')
    return list

assert solution("asdfadsf") == ['as', 'df', 'ad', 'sf']
assert solution("asdfads") == ['as', 'df', 'ad', 's_']
assert solution("") == []
assert solution("x") == ['x_']
def solution(s: str) -> list:
    if len(s) %2 != 0:
        s = s + '_'
    return [s[i:i+2] for i in range(0,len(s),2)]
1 个赞
def solution(s: str) -> list:
    if len(s) % 2 != 0:
        s = s + '_'
    lresult = []
    for i in range(0, len(s), 2):
        result = s[i:i + 2]
        lresult.append(result)
    return lresult


assert solution("asdfadsf") == ['as', 'df', 'ad', 'sf']
assert solution("asdfads") == ['as', 'df', 'ad', 's_']
assert solution("") == []
assert solution("x") == ['x_']
def solution(s: str) -> list:
    if len(s)%2!=0:
        s=s+'_'
    return [s[i:i+2] for i in range(0,len(s),2)]

assert solution("asdfadsf") == ['as', 'df', 'ad', 'sf']
assert solution("asdfads") == ['as', 'df', 'ad', 's_']
assert solution("") == []
assert solution("x") == ['x_']