简体   繁体   English

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

[英]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'

Consider using the textwrap library (it comes included in python3):考虑使用textwrap库(它包含在 python3 中):

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

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

相关问题 在Python中一定数量的字符出现多于一次之后,如何修剪字符串? - How do I trim a string after certain amount of characters appear more then once in Python? 如何只保留字符串的某一部分,以及后面的一定数量的字符 - How to keep only a certain part of a string, and a certain amount of characters after it 如何在python中的字符串之前打印一定数量的字符 - how to print a certain amount of characters before a string in python 在一定数量的字符后拆分字符串 - Spliting string after certain amount of characters 如何在字符串中的其他某些字符之后替换某些字符,Python? - How to replace certain characters after other certain characters in a string, Python? 如何获得等于一定数量字符的输入? - How do I get an input to equal a certain amount of characters? 如何从字符串中删除一定数量的字符 - How to remove a certain amount of characters from a string 如何在Python中的一定数量的单词后剥离字符串 - How to strip a string after a certain amount of words in python python在某些群集或字符后添加空间 - python adding space after certain clusters or characters 如何删除Python字符串中2个特定字符之后的字符? - How to remove characters after 2 certain characters in a Python string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM