繁体   English   中英

如何使用 python 在字符串中一定数量的字符后插入空格?

[英]How do I insert a space after a certain amount of characters in a string using python?

我需要在字符串中一定数量的字符后插入一个空格。 文本是一个没有空格的句子,每n个字符后需要用空格分隔。

所以它应该是这样的。

thisisarandomsentence

我希望它返回为:

this isar ando msen tenc e

我的 function 是:

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'

使用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'))

'这是 isar ando msen tenc e'

考虑使用textwrap库(它包含在 python3 中):

import textwrap
def encrypt(string, length):
      a=textwrap.wrap(string,length)
      return a

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM