Splitting a string every 'n'

Skip Montanaro skip at pobox.com
Tue Jul 9 15:10:20 EDT 2002


    Huaiyu> To work with any int n, change to one of these

    Huaiyu> rex = re.compile('.{,%s}'%n, re.DOTALL)  # keeps remainder segment

I think you want {1,%s}.  Note the spurious empty string at the end if at
least one character isn't required:

    >>> import re
    >>> rex = re.compile(r"(.{,4})")
    >>> re.findall(rex, "abcd")
    ['abcd', '']
    >>> rex = re.compile(r"(.{1,4})")
    >>> re.findall(rex, "abcd")
    ['abcd']
    >>> rex = re.compile(r"(.{,4})")
    >>> re.findall(rex, "abcde")
    ['abcd', 'e', '']
    >>> rex = re.compile(r"(.{1,4})")
    >>> re.findall(rex, "abcde")
    ['abcd', 'e']

-- 
Skip Montanaro
skip at pobox.com
consulting: http://manatee.mojam.com/~skip/resume.html





More information about the Python-list mailing list