[Tutor] Which way is better?

Chris C mysecretrobotfactory at gmail.com
Fri Oct 23 15:14:35 EDT 2020


Hi, I have two ways to do string operation, they both do the job fine, but
I have
been wondering if there is a reason to prefer either. Is it more pythonic
to use
the 2nd method? Which way is faster/better?

Please help. Thanks.

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, divided by ','

You can run the following code to see what I mean.

# Should I do this?
raw_string = '-4353,2339'

first_part = ''
second_part = ''

for n in range(len(raw_string)):
    if raw_string[n] == ',':
        first_part = raw_string[0:n]
        second_part = raw_string[n+1:]

print(int(first_part))
print(int(second_part))

# Or this?

raw_string = '-4353,2339'
raw_string = raw_string.split(',')
print(raw_string)
print(int(raw_string[0]))
print(int(raw_string[1]))


More information about the Tutor mailing list