[Tutor] Which way is better?
dn
PyTutor at DancesWithMice.info
Sat Oct 24 14:06:25 EDT 2020
On 24/10/2020 12:12, Alan Gauld via Tutor 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.
+1
taking "there usually is one to be found" a bit further: when comparing
'pythonic' approaches, two other criteria:
- how will the (two items of) data be used, afterwards?
- what of error conditions: zero integers, one integer/no comma,
non-integer data, multiple commas, ...
NB is it appropriate to call a *list* of *processed* strings "raw_string"?
--
Regards =dn
More information about the Tutor
mailing list