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'))
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
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)
添加回答
举报
