Slicing every element of a list

John Machin sjmachin at lexicon.net
Tue Jul 12 19:18:57 EDT 2005


Alex Dempsey wrote:
> Recently I tried to slice every element of a list of strings. First I tried:

"slice"? Interesting terminology. Next problem you have, try posting an 
example of your input, and your expected output.

E.g.
repr(input_string): '"foo"\t"barre"\t"zot"\t"X"\n'
repr(output_list): ['foo', 'barre', 'zot']

Then folk would be able to point out that the csv module might be a tad 
more appropriate -- it gives you a general solution.

I'm presuming that the hard-coded number "5" means that you have a 
single-character field at the end that you want to ignore. Your code 
would be more robust in the face of change were you to ignore the last 
field after splitting instead of the last 5 chars before splitting.

> 
> f = open("export.xls", "r")


Aarrgghh!! a file with a ".xls" extension that you can read as a text file??


> lines = f.readlines()
> 
> for line in lines:
>     line = line[1:-5]
>     line = line.split('\"\t\"')
> 
> This went without returning any errors, but nothing was sliced or
> split. Next I tried:
> 
> for i in range(len(lines)):
>     lines[i] = lines[i][1:-5]
>     lines[i] = lines[i].split('\"\t\"')
> 
> This of course worked, but why didn't the first one work. Further why
> didn't the first one return an error?



More information about the Python-list mailing list