所以我有一個字串 (string = "Cipher Programming - 101!"),我想將它分成六個字符(包括空格和特殊符號)并將結果存盤為 Python 中的串列。
預期輸出:['Cipher', 'Progr', 'amming', ' - 101', '!']
uj5u.com熱心網友回復:
只需一個普通的 for 回圈就可以了:
string = "Cipher Programming - 101!"
n = 6
[line[i:i n] for i in range(0, len(string), n)]
uj5u.com熱心網友回復:
上面的答案效果很好 - 非常緊湊和優雅,但為了更好地理解它,我決定包含一個帶有常規 for 回圈的答案。
string = "Cipher Programming - 101!" # can be any string (almost)
result = []
buff = ""
split_by = 6 # word length for each string inside of 'result'
for index, letter in enumerate(string):
buff = letter
# first append and then reset the buffer
if (index 1) % split_by == 0:
result.append(buff)
buff = ""
# append the buffer containing the remaining letters
elif len(string) - (index 1) == 0:
result.append(buff)
print(result) # output: ['Cipher', ' Progr', 'amming', ' - 101', '!']
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450099.html
標籤:Python python-3.x 细绳 列表 分裂
上一篇:熊貓爆炸多列
