12

文字列内の一定量の文字の後にスペースを挿入する必要があります。テキストはスペースのない文であり、n 文字ごとにスペースで区切る必要があります。

したがって、このようなものになるはずです。

thisisarandomsentence

そして私はそれを次のように返したい:

this isar ando msen tenc e

私が持っている機能は次のとおりです。

def encrypt(string, length):

とにかくpythonでこれを行うことはありますか?

4

4 に答える 4

22
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'
于 2012-04-09T07:54:33.070 に答える
2
import re
(' ').join(re.findall('.{1,4}','thisisarandomsentence'))

「this isar ando msen tenc e」

于 2020-07-22T03:27:05.520 に答える
2

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'
于 2012-04-09T08:06:33.360 に答える