3

I am trying to get Python to allow me to insert a space at regular intervals (every 5th character), in a string. This is my code:

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

however it groups the first section together as 7. Can anyone help me fix this?

Nayuki
  • 17,911
  • 6
  • 53
  • 80
  • `import textwrap; print(' '.join(textwrap.wrap("abcdefghijklmnopqrstuvwxyz", 5)))` – idjaw Feb 26 '16 at 22:03
  • 1
    Just use `" ".join(str1[i:i + 5] for i in range(0, len(str1), 5))`. One of my highest scoring answers was for that one line. – zondo Feb 26 '16 at 22:04

2 Answers2

3

Very easy with a regex:

>>> import re
>>> ' '.join(re.findall(r'.{1,5}', str1))
'abcde fghij klmno pqrst uvwxy z'

Or use a slice:

>>> n=5
>>> ' '.join([str1[i:i+n] for i in range(0, len(str1), n)])
'abcde fghij klmno pqrst uvwxy z'
dawg
  • 98,345
  • 23
  • 131
  • 206
0

In a step by step script:

You can use the string module to get all the ascii letters in lowercase:

from string import ascii_lowercase

Now, you can iterate every five characters and add a space using the following:

result = ""
for i in range(0,len(ascii_lowercase), 5):
    result += ascii_lowercase[i:i+5] + ' '
print(result)

Prints the following result:

abcde fghij klmno pqrst uvwxy z
kikocorreoso
  • 3,999
  • 1
  • 17
  • 26