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']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With