Problem using s.strip() to remove leading whitespace in .csv file

Peter Otten __peter__ at web.de
Wed Feb 29 09:53:38 CET 2012


Guillaume Chorn wrote:

> Hello All,
> 
> I have a .csv file that I created by copying and pasting a list of all the
> players in the NBA with their respective teams and positions (
> http://sports.yahoo.com/nba/players?type=lastname&first=1&query=&go=GO!).
> Unfortunately, when I do this I have no choice but to include a single
> leading whitespace character for each name.  I'd like to compare this list
> of names to another list (also in .csv format but in a different file)
> using a simple Python script, but in order to do that I need to strip the
> leading whitespace from all of the names or none of them will match the
> names in the second list.  However, when I try to do this as follows:
> 
> positions = open('/home/guillaume/Documents/playerpos.csv')
> 
> for line in positions:
>     info = line.split(',')
>     name = info[0]
>     name = name.strip()
>     print name #to examine the effect of name.strip()
> 
> I keep getting all of the names with the leading whitespace character NOT
> removed (for example: " Jeff Adrien". Why is this happening?

Do you mean

print name.strip()

still prints a leading space? If so, what does 

print repr(name)

print? If it is

"\xc2\xa0Jeff Adrien"

try 

print name.decode("utf-8").strip()

Or do you mean the effect of strip() is not permanent? You have to modify 
the line then:

cleaned_lines = []
for line in positions:
    info = line.split(",")
    info[0] = info[0].strip()
    cleaned_lines.append(",".join(info))
positions = cleaned_lines

 
> The following is a sample of the .csv file (the one I'm trying to remove
> the whitespace from) opened in gedit, the built-in Ubuntu text editor:
> 
>  Jeff Adrien,SF,Houston Rockets
>  Arron Afflalo,SG,Denver Nuggets
>  Maurice Ager,GF,Minnesota Timberwolves
>  Blake Ahearn,PG,Los Angeles Clippers
>  Alexis Ajinca,FC,Toronto Raptors
>  Solomon Alabi,C,Toronto Raptors
>  Cole Aldrich,C,Oklahoma City Thunder
>  LaMarcus Aldridge,FC,Portland Trail Blazers
>  Joe Alexander,SF,New Orleans Hornets
>  Lavoy Allen,FC,Philadelphia 76ers
>  Malik Allen,FC,Orlando Magic
>  Ray Allen,SG,Boston Celtics
>  Tony Allen,GF,Memphis Grizzlies
>  Lance Allred,C,Indiana Pacers
>  Rafer Alston,PG,Miami Heat
> 
> Any help with this seemingly simple but maddening issue would be much
> appreciated.
> 
> thanks,
> Guillaume





More information about the Python-list mailing list