按一定数量拆分字符串并将结果保存为 python 中的列表
split string by certain number and save the result as a list in python
所以我有一个字符串 (string = "Cipher Programming - 101!"),我想将它分成六个字符
(包括空格和特殊符号)并将结果存储为 Python.
中的列表
预期输出:['Cipher'、“Progr”、'amming'、“- 101”、“!”]
只需一个普通的 for 循环就可以解决问题:
string = "Cipher Programming - 101!"
n = 6
[line[i:i+n] for i in range(0, len(string), n)]
上面的答案非常有效 - 非常紧凑和优雅,但为了更好地理解它,我决定包含一个带有常规 for-loop.
的答案
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', '!']
所以我有一个字符串 (string = "Cipher Programming - 101!"),我想将它分成六个字符 (包括空格和特殊符号)并将结果存储为 Python.
中的列表预期输出:['Cipher'、“Progr”、'amming'、“- 101”、“!”]
只需一个普通的 for 循环就可以解决问题:
string = "Cipher Programming - 101!"
n = 6
[line[i:i+n] for i in range(0, len(string), n)]
上面的答案非常有效 - 非常紧凑和优雅,但为了更好地理解它,我决定包含一个带有常规 for-loop.
的答案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', '!']