Greedy regex breaks python every nth line

My question is similar to this one , but with some changes. First of all, I need to use python and regex. My line: "Four points and seven years ago." and I want to break it into every sixth character, but also, in the end, if the characters are not divisible by 6, I want to return the spaces.

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

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

The closest I can get is an attempt that ignores my period and doesn't give me spaces

 re.findall('.{%s}'%6,'Four score and seven years ago.') #split into strings ['Four s', 'core a', 'nd sev', 'en yea', 'rs ago'] 
+5
source share
3 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 gives spaces at the end that you requested.

Alternatively, if you should 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 to create an ss string that has at its disposal sufficient empty space.

+4
source

The reason you don’t get the finite element containing the period is because your string is not a multiple of 6. Therefore, you need to change the regular expression according to 1-6 characters at a time:

 >>> re.findall('.{1,6}','Four score and seven years ago.') ['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '.'] 

To get the desired complement to your last element, simply use this:

 >>> [match.ljust(6, ' ') for match in re.findall('.{1,6}','Four score and seven years ago.')] ['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '. '] 
+3
source

You can use this:

 >>> re.findall('(.{6}|.+$)', 'Four score and seven years ago.') ['Four s', 'core a', 'nd sev', 'en yea', 'rs ago', '.'] 
+1
source

Source: https://habr.com/ru/post/1237026/


All Articles