0

I want to split a string like this. I can do the following.

f1, f2, f3, f4, f5 = 'field1_field2_field3_field4_field5'.split('_')

However, I only need let's say f1 and f4. I do not want to assign other fields (I do not want to keep the others in the memory). I guess I am looking for something like Perl's array slice notation.

Supertech
  • 746
  • 1
  • 9
  • 25
  • 1
    See also https://stackoverflow.com/questions/18272160/access-multiple-elements-of-list-knowing-their-index – Ry- Feb 25 '23 at 00:28

3 Answers3

3

You could assign to _ to indicate an unused value. (Note that this is only a convention and _ is just a regular variable here.)

f1, *_, f4, _ = 'field1_field2_field3_field4_field5'.split('_')
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

You could use slicing.

f1, f4 = 'field1_field2_field3_field4_field5'.split('_')[0:4:3]

This has the benefit of not assigning to other names. For this particular case, [0:n:3] where n>3 or n=-1 will work.

In general, to extract two elements from a sequence that are at indices a and b where b>a, using [a:b+1:b-a] is typically the easiest solution.

Mous
  • 953
  • 3
  • 14
0

You could repeat intermediate variable names for fields you won't assign

f1, f4, f4, f4 = 'field1_field2_field3_field4_field5'.split('_')[:4]

But the saving in trivial memory allocation is probably not worth the loss in code clarity.

Alternatively, you could add one last None value to the unpacking list so the the _ always ends up with a None value unallocating any intermediate values :

(f1, _, _, f4, *_), _ = 'field1_field2_field3_field4_field5'.split('_'),None
Alain T.
  • 40,517
  • 4
  • 31
  • 51