1

I have the following string for example:

a-b-c-d-e-f

I want to remove the first element and the last two elements so the output will be:

b-c-d 

I tried to use rsplit, But the output is list:

print string.rsplit('-',)[1:-2]
['b', 'c', 'd']

How can i combine the list element back to be a string? Is there any easier way to remove the elements instead of using rsplit?

Omri
  • 1,436
  • 7
  • 31
  • 61
  • 3
    https://stackoverflow.com/a/1876211/3462319 – depperm Oct 09 '18 at 14:34
  • 1
    string = '-'.join(new_string) where new_string is the split list – Rahul Agarwal Oct 09 '18 at 14:35
  • Thanks guys. Works great! – Omri Oct 09 '18 at 14:37
  • Here's [another website](https://www.geeksforgeeks.org/join-function-python/) that explains str.join, even using your delimiters. – David Culbreth Oct 09 '18 at 14:39
  • @gofvonx, I don't think this is a dupe of that one, simply because the approach for the answer is so different. This question comes with no knowledge of the function, so finding the one you referenced might be difficult. That being said. I think there is value in reading through some of the [language documentation](https://docs.python.org/3.6/library/stdtypes.html#str.join) surrounding a question before asking it here. – David Culbreth Oct 09 '18 at 14:42

2 Answers2

4

You can just combine calls to split and rsplit:

a = "a-b-c-d-e-f"
b = a.split("-", 1)[-1].rsplit("-", 2)[0]

But that is just for the "cool puzzle effect". The more maintainable approach is certainly to split the string at the - separator, operate on the data as a list, and then use join to assemble it back:

a = "a-b-c-d-e-f"
b = a.split("-")
c = b[1:-2]
d = "-".join(c)

Or everything run together, if you prefer:

b = "-".join(a.split("-")[1:-2])
jsbueno
  • 99,910
  • 10
  • 151
  • 209
1

rsplit returns the list, you need to join the elements of the returned list with '-' to get the desired result.

'-'.join(string.rsplit('-',)[1:-2])
fahad
  • 66
  • 4