Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python split function to extract the first element and last element

Tags:

python

  python code --> ",".join("one_two_three".split("_")[0:-1])

I want to take the 0th element and last element of delimited string and create a new string put of it . The code should delimited string of any length

Expected output : "one,three"

The above code gives me

   'one,two'

Can some one please help me

like image 696
Surender Raja Avatar asked Mar 11 '26 22:03

Surender Raja


1 Answers

[0:-1] is a slice, it returns all the elements from 0 to the 2nd-to-last element.

Without the third stride parameter, which is used for getting every Nth element, a slice can only return a contiguous portion of a list, not two separate items.

You should select the first and last separately, then concatenate them.

items = "one_two_three".split("_")
result = f"{items[0]},{items[-1]}"
like image 101
Barmar Avatar answered Mar 14 '26 11:03

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!