user17733112
user17733112

Reputation:

How to remove the last character of a string and return removed one?

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.

Upvotes: 0

Views: 819

Answers (3)

qraxiss
qraxiss

Reputation: 126

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)

Upvotes: 1

Tomerikoo
Tomerikoo

Reputation: 19414

You can use the rpartition string method:

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

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

Gives:

abcadlfo
g

Upvotes: 2

user459872
user459872

Reputation: 24602

You can use unpacking syntax.

>>> s = 'abcadlfog'
>>> *first, last = s
>>> "".join(first)
'abcadlfo'
>>> last
'g'

Upvotes: 3

Related Questions