The Python Oracle

Get the last 4 characters of a string

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle

--

Chapters
00:00 Get The Last 4 Characters Of A String
00:15 Accepted Answer Score 1058
00:41 Answer 2 Score 86
00:48 Thank you

--

Full question
https://stackoverflow.com/questions/7983...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string

#avk47



ACCEPTED ANSWER

Score 1058


Like this:

>>> mystr = "abcdefghijkl"
>>> mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>> mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.




ANSWER 2

Score 86


str = "aaaaabbbb"
newstr = str[-4:]

See : http://codepad.org/S3zjnKoD