Newbie Q: efficiency of list -> string conversion
Jeff Shannon
jeff at ccvcorp.com
Mon Nov 19 21:26:39 EST 2001
More information about the Python-list mailing list
Mon Nov 19 21:26:39 EST 2001
- Previous message (by thread): Newbie-ish question
- Next message (by thread): Newbie Q: efficiency of list -> string conversion
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Erik Johnson wrote: > I am wondering about the efficiency of converting a list of single > characters into the corresponding string. Here is a trivial example: > > s = "string" > l = list(s) > l.reverse() > > rv = "" > for i in xrange(len(l)): > rv += l[i] > > print rv > > This works, but in general, this seems grossly inefficient for large > lists. Yes, you want to use the string method join()-- s = "string" l = list(s) l.reverse() rv = "".join(l) print rv join() will return a string that's created from all the elements in the list passed to it, separated by copies of the string that it's called on. In the example above, it's called on the empty string ( "" ). You could also use it to create, for example, a string of comma-separated or tab-separated fields-- l = [ 'field1', 'field2', 'field3' ] print ",".join(l) print "\t".join(l) Jeff Shannon Technician/Programmer Credit International
- Previous message (by thread): Newbie-ish question
- Next message (by thread): Newbie Q: efficiency of list -> string conversion
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list