2016-02-26 71 views
2

我想让Python在一个字符串中定期插入一个空格(每第5个字符)。 这是我的代码:Python 3.4-定期插入空格

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 谁能帮助我解决这个问题?

+0

'进口textwrap; print(''.join(textwrap.wrap(“abcdefghijklmnopqrstuvwxyz”,5)))' – idjaw

+1

只需使用'“”.join(str1 [i:i + 5]为范围(0,len(str1),5 ))'。我得分最高的答案之一就是那条线。 – zondo

回答

0

在一步步脚本:

可以使用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 
1

很容易与正则表达式:

>>> 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'