Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last 4 characters of a string [duplicate]

Tags:

python

string

I have the following string: "aaaabbbb"

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

like image 642
jkjk Avatar asked Nov 02 '11 16:11

jkjk


People also ask

How do I get the last 5 characters of a string?

To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.

How do I get the last 4 characters of a string in Python?

To access the last 4 characters of a string in Python, we can use the subscript syntax [ ] by passing -4: as an argument to it. -4: is the number of characters we need to extract from the end position of a string.

How do I print the last 3 characters of a string?

string str = "AM0122200204"; string substr = str. Substring(str. Length - 3);


2 Answers

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.

like image 85
Constantinius Avatar answered Sep 29 '22 18:09

Constantinius


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

See : http://codepad.org/S3zjnKoD

like image 26
DhruvPathak Avatar answered Sep 29 '22 18:09

DhruvPathak