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.
CodePudding user response:
You can use unpacking syntax.
>>> s = 'abcadlfog'
>>> *first, last = s
>>> "".join(first)
'abcadlfo'
>>> last
'g'
CodePudding user response:
You can use the rpartition
string method:
s = 'abcadlfog'
result, last, _ = s.rpartition(s[-1])
print(result, last, sep='\n')
Gives:
abcadlfo
g
CodePudding user response:
To remove the last character from a string and save it to another variable, you can use the following approach:
s = 'abcadlfog'
last_char = s[-1]
result = s[:-1]
This will create a new string called result
that is a copy of s
with the last character removed, and the last character will be saved to the variable last_char
.
CodePudding user response:
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)