[英]How do I insert a space after a certain amount of characters in a string using python?
I need to insert a space after a certain amount of characters in a string.我需要在字符串中一定数量的字符后插入一个空格。 The text is a sentence with no spaces and it needs to be split with spaces after every n characters.
文本是一个没有空格的句子,每n个字符后需要用空格分隔。
so it should be something like this.所以它应该是这样的。
thisisarandomsentence
and i want it to return as:我希望它返回为:
this isar ando msen tenc e
the function that I have is:我的 function 是:
def encrypt(string, length):
is there anyway to do this on python?有没有办法在 python 上做这个?
def encrypt(string, length):
return ' '.join(string[i:i+length] for i in range(0,len(string),length))
encrypt('thisisarandomsentence',4)
gives encrypt('thisisarandomsentence',4)
给出
'this isar ando msen tenc e'
Using itertools
grouper recipe :使用
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'
import re
(' ').join(re.findall('.{1,4}','thisisarandomsentence'))
'this isar ando msen tenc e' '这是 isar ando msen tenc e'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.