opinion for newbie code

David M. Wilson dw-google.com at botanicus.net
Sat Feb 14 21:22:18 EST 2004


robsom wrote:

> 3.	row = line.replace(" ","").replace(";","").replace("\n","").split(":")

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

It is common practise, that's not to say it's good practise. An 
alternative way of doing this might be:

	row = re.split(r'[\s;:]+', line)

If you have never encountered regular expressions before, then lucky 
you. They do have a tendancy to be efficient, and thats probably the 
only time you should need them.

To save you a years' Googling, here's what the above does:

	[\s;:]
	Match any character that is whitespace (\s), a semicolon, or
	a colon.

	+
	One or more times.

	re.split(pattern, data)
	Split <data> at every occurrence of <pattern>, returning the
	result as a list.


For added performance, using "compiled = re.compile(pattern)", then 
passing <compiled> instead of <pattern> will increase speed.


David.




More information about the Python-list mailing list