为了账号安全,请及时绑定邮箱和手机立即绑定

拆分 Python 字符串

拆分 Python 字符串

斯蒂芬大帝 2022-10-18 15:53:31
将字符串分成两个字符对。如果字符串包含奇数个字符,则最后一对中缺少的第二个字符应替换为下划线 ('_')。输入:一个字符串。输出:一个可迭代的字符串。例子:split_pairs('abcd') == ['ab', 'cd'] split_pairs('abc') == ['ab', 'c_']
查看完整描述

4 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

import textwrap


def split_pairs(input):

    # Use textwrap to split the input into chunks of two characters

    split = textwrap.wrap(input, 2)


    # In your example I see you want a "_" if string is odd length

    # Check the length of the last chunk, and if it is 1, add a "_"


    if len(split[-1]) == 1:

        split[-1] += "_"

    return split



print(split_pairs('abcd'))

print(split_pairs('abc'))


查看完整回答
反对 回复 2022-10-18
?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

我的解决方案是:


import re


def solution(s):

    return re.findall(".{2}", s + "_")


查看完整回答
反对 回复 2022-10-18
?
心有法竹

TA贡献1866条经验 获得超5个赞

试试这个没有导入的简短函数:


def split_pairs(inp):

    pairs = [inp[2*i:2*i+2] for i in range(len(inp) // 2)]

    if len(inp) % 2 == 1:

        pairs.append(f'{inp[-1]}_')

    return pairs


查看完整回答
反对 回复 2022-10-18
?
慕容森

TA贡献1853条经验 获得超18个赞

st = input('Input a string:')

arr = [] 

if len(st)%2==0:

    for i in range(0,len(st)-1,2):

        arr.append(st[i]+st[i+1])

else:

    st +='_'

    for i in range(0,len(st)-1,2):

        arr.append(st[i]+st[i+1])

print(arr)

另外,如果您想输入长文本并在输入后尝试 st = st.replace(' ','') 去除空格:


st = input('Input a string:')

st = st.replace(' ','')

arr = [] 

if len(st)%2==0:

    for i in range(0,len(st)-1,2):

        arr.append(st[i]+st[i+1])

else:

    st +='_'

    for i in range(0,len(st)-1,2):

        arr.append(st[i]+st[i+1])

print(arr)


查看完整回答
反对 回复 2022-10-18
  • 4 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号