猿问

拆分 Python 字符串

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

输入:一个字符串。

输出:一个可迭代的字符串。

例子:

split_pairs('abcd') == ['ab', 'cd']
split_pairs('abc') == ['ab', 'c_']


斯蒂芬大帝
浏览 151回答 4
4回答

繁花如伊

import textwrapdef 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 splitprint(split_pairs('abcd'))print(split_pairs('abc'))

慕桂英4014372

我的解决方案是:import redef solution(s):    return re.findall(".{2}", s + "_")

心有法竹

试试这个没有导入的简短函数: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

慕容森

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)
随时随地看视频慕课网APP

相关分类

Python
我要回答