Skip to content Skip to sidebar Skip to footer

Python 3.4- Inserting Spaces At Regular Intervals

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 = [] lis

Solution 1:

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 inrange(0, len(str1), n)])
'abcde fghij klmno pqrst uvwxy z'

Solution 2:

In a step by step script:

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

fromstringimport ascii_lowercase

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

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

Prints the following result:

abcde fghij klmno pqrst uvwxy z

Post a Comment for "Python 3.4- Inserting Spaces At Regular Intervals"