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 from Constantinius on Stack OverflowLike 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.
str = "aaaaabbbb"
newstr = str[-4:]
See : http://codepad.org/S3zjnKoD
python - Extract the last n characters of a string in a list - Stack Overflow
Python- get last 2 characters of a string - Stack Overflow
shell script - Print last N characters from all lines in a file using cut - Unix & Linux Stack Exchange
How to extract last three characters of a string?
I can't for the life of me find any documentation on how to do this so I apologize.
In python its
string = "D:\\nim\\nim.zip" print(string[-4:])
This outputs .zip. I can see in Nim how to slice a string from the start (0 .. ^4) but not backwards. Is this possible without writing a huge function?
cut by itself doesn't have the concept of "the last N characters" on a line. However if you combine this with the rev program you can reverse each line, select the first N characters, and then reverse the result to get things back to the original order.
rev | cut -c 1-3 | rev
If on a GNU system, you probably want to avoid cut which only works correctly with single-byte characters.
You could use sed instead:
sed -n '/^.*\(...\)$/\1/p' < file
(skips the lines that have fewer than 3 characters and possibly non-text lines with some implementations).
Or to include the lines that contain fewer than 3 characters, printing only what there is:
sed -n 's/.\{0,3\}$/\
&/; s/^.*\n//p' < file