Get the last 4 characters of a string

PythonString

Python Problem Overview


I have the following string: "aaaabbbb"

How can I get the last four characters and store them in a string using Python?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

See : http://codepad.org/S3zjnKoD

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjkjkView Question on Stackoverflow
Solution 1 - PythonConstantiniusView Answer on Stackoverflow
Solution 2 - PythonDhruvPathakView Answer on Stackoverflow