Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

greedy regex split python every nth line

My question is similar to this one, but with some modifications. First off I need to use python and regex. My string is: 'Four score and seven years ago.' and I want to split it by every 6th character, but in addition at the end if the characters do not divide by 6, I want to return blank spaces.

I want to be able to input: 'Four score and seven years ago.'

And ideally it should output: ['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '. ']

The closest I can get is this attempt, which ignores my period and does not give me the blank spaces

re.findall('.{%s}'%6,'Four score and seven years ago.') #split into strings
['Four s', 'core a', 'nd sev', 'en yea', 'rs ago']
like image 485
Bobe Kryant Avatar asked Nov 29 '15 01:11

Bobe Kryant


1 Answers

This is easy to do without regular expressions:

>>> s = 'Four score and seven years ago.'
>>> ss = s + 5*' '; [ss[i:i+6] for i in range(0, len(s) - 1, 6)]
['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '.     ']

This provides the blank spaces at the end that you asked for.

Alternatively, if you must use regular expressions:

>>> import re
>>> re.findall('.{6}', ss)
['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '.     ']

The key in both cases is creating the string ss which has enough blank space at the end.

like image 147
John1024 Avatar answered Oct 25 '22 21:10

John1024