trailing newline in string.splitfields()

Bengt Richter bokr at
Tue Sep 3 19:45:17 EDT 2002

On Tue, 03 Sep 2002 14:17:10 GMT, Micah Mayo <astrophels at> wrote:

>I was splitting up some fields in a textfile using string.split, which 
>works fine, but that it usee ' ' as the delimiter. I've found that some 
>of the things I want to split include a space or two, so I've gone to 
>using string.splitfields, which also works fine, but for one thing.
AFAICT string.splitfields is now an alias for string.split. The docs say
splitfields(s[, sep[, maxsplit]]) 
      This function behaves identically to split(). (In the past, split() was only used
      with one argument, while splitfields() was only used with two arguments.) 

>Unlike string.split() it also grabs the newlne('\n') at the end of each 
>The way I've worked around this is as such:
>var1,var2,var3 = string.splitfields(stringtosplit,',')
 ^^^^--you really ought not to use builtin names for variables ;-)

If you are not otherwise using the three var's, you could write


if you don't care about leading or trailing whitespace. Otherwise, to duplicate
what you are doing, you could write



 >>> myList = list('abc')
 >>> myList
 ['a', 'b', 'c']
 >>> stringtosplit = '  <-2sp..1sp-> ,no_spaces,inside spaces and end.\n'
 >>> myList.extend(stringtosplit[:-1].split(','))
 >>> myList
 ['a', 'b', 'c', '  <-2sp..1sp-> ', 'no_spaces', 'inside spaces and end.']

>So, I slice of the character, easy enough. And I'm generally satisfied 
>with that - but I was wondering if there may be, for the cause of more 
>beautiful code, a way to tell string.splitfields() to do it automatically.
Regular expressions will let you do things like splitting on comma with
optional white space on either side of the comma, but not touching white
space elsewhere. Or ignore delimiters inside of quotations, etc. You might
not need those options every time, but sometimes you do.

Bengt Richter

More information about the Python-list mailing list