opinion for newbie code

Peter Otten __peter__ at web.de
Sun Feb 15 06:02:14 EST 2004


robsom wrote:

> I have strings of like this:
> "one          two : three four     ;\n"
> and I want to put them into lists using ":" as delimeter but I have to
> get rid of all the spaces and other not necessary characters, like this:
> list = ["onetwo", "threefour"]
> 
> so I wrote the following code, which works, but I have a couple of
> questions:
> 
> 1. for line in fin.readlines():
> 2.    eq = []
> 3.    row = line.replace(" ","").replace(";","").replace("\n","").split(":")
> 4.    # ...
> 5.    # other code
> 6.    # result of the code are three lists A, B, C
> 7.    # which I want to put into a single list L = ['A','B','C']
> 8.    # ...
> 9.    L.append(A)
> 10.   L.append(B)
> 11.   L.append(C)
> 
> Question n.1: what do you think of statement number 3? it works but I
> kind of suspect it is not the best way to do it.

Outside the for loop:

>>> import string
>>> t = string.maketrans("", "")
>>> d = " ;\n" # list all chars you want to remove
>>> line = "one          two : three four     ;\n"

In the for loop:

>>> line.translate(t, d).split(":")
['onetwo', 'threefour']

> Question n.2: on line 9-11 I add my three lists (A, B, C) to the L list
> using three append instructions. Is there another way to do the same
> thing, i.e. to add more than one element to a list with a single
> instruction?

L.extend([A, B, C])

However, I suppose this is slightly less efficient, as you have to build the
intermediate list [A, B, C].

Peter



More information about the Python-list mailing list