how to remove comma while using split() function?
Eddie Corns
eddie at holyrood.ed.ac.uk
Fri May 23 14:38:34 EDT 2003
regnivon at netscape.net (scn) writes:
>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 you're sure that the fields are seperated by exactly ", " you could do:
firstname,lastname = line.split(', ',1)
perhaps a more generic approach would be
from string import strip
...
firstname,lastname = map(strip, line.split(',',1))
Or in fact (sticking with the first example):
tup = tuple (line.split(', ',1))
data.append (tup)
and finally:
for line in input:
data.append (tuple (line.split(', ',1)))
or
for line in input:
data.append (tuple (map(strip, line.split(',',1))))
if you prefer that way. Which should also show you why 'tuple' isn't a good
name for a variable.
More information about the Python-list
mailing list