527

I have the following string: "aaaabbbb"

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

Anders
  • 8,307
  • 9
  • 56
  • 88
jkjk
  • 5,777
  • 4
  • 20
  • 19

2 Answers2

1039

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.

Constantinius
  • 34,183
  • 8
  • 77
  • 85
  • 10
    I remember it like this, -4 is short hand for (length - 4) – adnan2nd Sep 16 '18 at 15:21
  • +1, this is pure gold... There I was faffing around with `len(str(p)) - str(p[len(str(reversed(str(p))).split(' ', 1))[0])], len(str(p)), 2)` to get the last *n* letters of `p` based on the first space. Useless and doesn't even work. – Benj Apr 09 '19 at 16:38
  • Remember the `:`, otherwise you'll just get the 4th last character! – Alison Bennett Mar 06 '20 at 01:06
84
str = "aaaaabbbb"
newstr = str[-4:]

See : http://codepad.org/S3zjnKoD

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175