-
繁花如伊
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)