Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.4-定期插入空格_Python - Fatal编程技术网

Python 3.4-定期插入空格

Python 3.4-定期插入空格,python,Python,我试图让Python允许我以固定的间隔(每5个字符)在字符串中插入一个空格。 这是我的代码: str1 = "abcdefghijklmnopqrstuvwxyz" list1 = [] list2 = [] count = 3 space = " " # converting string to list for i in str1: list1.append(i) print(list1) # inserting spaces for i in list1: mod =

我试图让Python允许我以固定的间隔(每5个字符)在字符串中插入一个空格。 这是我的代码:

str1 = "abcdefghijklmnopqrstuvwxyz"
list1 = []
list2 = []
count = 3
space = " "

# converting string to list
for i in str1:
    list1.append(i)
print(list1)

# inserting spaces
for i in list1:
    mod = count%6
    count = count + 1
    if mod == 0:
        list1.insert(count,space)
        count = count + 1
#converting back to a string
list2 = "".join(list1)
print(str(list2))
但是,它将第一部分组合为7。
有人能帮我解决这个问题吗?

在一个分步脚本中:

您可以使用
string
模块获取所有小写ascii字母:

from string import ascii_lowercase
现在,您可以每五个字符迭代一次,并使用以下命令添加一个空格:

result = ""
for i in range(0,len(ascii_lowercase), 5):
    result += ascii_lowercase[i:i+5] + ' '
print(result)
打印以下结果:

abcde fghij klmno pqrst uvwxy z

使用正则表达式非常简单:

>>> import re
>>> ' '.join(re.findall(r'.{1,5}', str1))
'abcde fghij klmno pqrst uvwxy z'
或者使用切片:

>>> n=5
>>> ' '.join([str1[i:i+n] for i in range(0, len(str1), n)])
'abcde fghij klmno pqrst uvwxy z'
导入文本包装;打印(“”.join(textwrap.wrap(“abcdefghijklmnopqrstuvwxyz”,5))
只需使用
“”。对于范围(0,len(str1),5)中的i,使用str1[i:i+5])
。我得分最高的答案之一就是那一行。