[Tutor] Which way is better?

Chris C mysecretrobotfactory at gmail.com
Fri Oct 23 19:58:56 EDT 2020


cool, thanks!


On Fri, Oct 23, 2020 at 4:14 PM Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 23/10/2020 20:14, Chris C wrote:
>
> > the 2nd method? Which way is faster/better?
>
> Those two terms are often result in contradictory answers.
> But in this case not so...
>
> > The purpose of the following code is to turn a string, such as
> > '-4353,2339'into 2 int(),  by splitting the raw string into two,
>
> > for n in range(len(raw_string)):
> >     if raw_string[n] == ',':
> >         first_part = raw_string[0:n]
> >         second_part = raw_string[n+1:]
>
> > # Or this?
> >
> > raw_string = raw_string.split(',')
>
> The second.
> Reasons?
> 1) It's shorter and easier to type
> 2) It's more readable - the meaning is in the name - split
> 3) It's faster because the library code is in C.
> 4) The compiler will tell you if you spell it wrong
> 5) It works. (the for loop breaks if there is no comma in the string!)
>
> The first one isn't even a good Python version.
> It iterates over the string when you could use
> the find() method to locate the ',' and slice based
> on that. Any time you write a for loop in Python
> that iterates over range(len(x)) you should think
> again and check for a better solution, there usually
> is one to be found.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list