0

If I have a string:

s = 'abcadlfog'

I want to remove the last character from it but I should get that last one saved to another variable.

result = s[:-1]

I tried this but it only returns copy of the new string.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Abdulaziz
  • 1
  • 3

3 Answers3

3

You can use unpacking syntax.

>>> s = 'abcadlfog'
>>> *first, last = s
>>> "".join(first)
'abcadlfo'
>>> last
'g'
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
2

You can use the rpartition string method:

s = 'abcadlfog'
result, last, _ = s.rpartition(s[-1])

print(result, last, sep='\n')

Gives:

abcadlfo
g
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

As shown above, you can also use the s.rpartition method, but I think slicing looks better to the eye.

s = 'abcadlfog'
result, last = s[:-1], s[-1]

print(first, last)

Also, there is no noticeable difference in performance between the two codes. The choice is yours.

>>> %timeit result, last, _ = s.rpartition(s[-1])
53.3 ns ± 0.262 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

>>> %timeit result, last = s[:-1], s[-1]
52.7 ns ± 0.392 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
qraxiss
  • 36
  • 1
  • 5