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)
添加回答
舉報