文字列内の一定量の文字の後にスペースを挿入する必要があります。テキストはスペースのない文であり、n 文字ごとにスペースで区切る必要があります。
したがって、このようなものになるはずです。
thisisarandomsentence
そして私はそれを次のように返したい:
this isar ando msen tenc e
私が持っている機能は次のとおりです。
def encrypt(string, length):
とにかくpythonでこれを行うことはありますか?
def encrypt(string, length):
return ' '.join(string[i:i+length] for i in range(0,len(string),length))
encrypt('thisisarandomsentence',4)与える
'this isar ando msen tenc e'
import re
(' ').join(re.findall('.{1,4}','thisisarandomsentence'))
「this isar ando msen tenc e」
itertoolsハタのレシピを使用:
>>> from itertools import izip_longest
>>> def grouper(n, iterable, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
>>> text = 'thisisarandomsentence'
>>> block = 4
>>> ' '.join(''.join(g) for g in grouper(block, text, ''))
'this isar ando msen tenc e'