how to remove comma while using split() function?

Anton Muhin antonmuhin at sendmail.ru
Fri May 23 14:30:10 EDT 2003


scn wrote:
> hello. 
> i wrote a program to extract first and last names from a flat file and
> populate a mysql database.  It worked the first time, belive it or
> not. however, the comma after the first name is in the "firstname"
> record and i'd like to understand in my "line.split()" function how to
> remove the comma before populating the database.  thanks for your
> help.
> 
> the following are snippets from my program:
> 
> <snip>
> # open a file for reading
> # this file contains a list of first and last names, separated by a
> comma
> # example 'firstname1, lastname1'
> input = open('c:/python22/programs/database stuff/names.txt', 'r')
> 
> <snip>
> # loop directly on the file open for reading - xreadlines is
> obsolescent
> for line in input:
>     # split selectivley so most whitespaces in the line's not
> disturbed
>     firstname, lastname = line.split(None, 1)
>     tuple = (firstname, lastname)
>     # and append to data[] list
>     data.append(tuple)

If first and last name are separated with ", " sequence, you may use 
.split(", "):

 >>> s = "Bailey, James"
 >>> s.split(", ")
['Bailey', 'James']
 >>>

If number of spaces can vary, then you better with the following:

 >>> s = "Bailey, James"
 >>> t = s.split(',')
 >>> t[1] = t[1].lstrip()
 >>> t
['Bailey', 'James']
 >>>

And several notes: tuple in Python2.2 is a name of type and it's usually 
not a good idea to shadow this (some trciky to find bugs can arise). 
Thereofre your snippet I'd rewrite in the following way:

      t = tuple(line.split(None, 1))
      data.append(t)

or even one-liner:
      data.append(tuple(line.split(None, 1))

hth,
anton.





More information about the Python-list mailing list