how to remove comma while using split() function?

sismex01 at hebmex.com sismex01 at hebmex.com
Fri May 23 14:15:57 EDT 2003


> From: regnivon at netscape.net [mailto:regnivon at netscape.net]
> Sent: Friday, May 23, 2003 1:09 PM
> 
> 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.

Not hard to believe at all; python's like that.

> 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)
>

You could also split on the first comma, and then strip()
the resulting strings to eliminate leading and trainling
whitespace:

    firstname, lastname = line.split(",",1)
    tuple = (firsname.strip(), lastname.strip())

HTH

-gca
Advertencia:La informacion contenida en este mensaje es confidencial y
restringida, por lo tanto esta destinada unicamente para el uso de la
persona arriba indicada, se le notifica que esta prohibida la difusion de
este mensaje. Si ha recibido este mensaje por error, o si hay problemas en
la transmision, favor de comunicarse con el remitente. Gracias.





More information about the Python-list mailing list