I have the following string: "aaaabbbb"
How can I get the last four characters and store them in a string using Python?
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.
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.
string str = "AM0122200204"; string substr = str. Substring(str. Length - 3);
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.
str = "aaaaabbbb" newstr = str[-4:]
See : http://codepad.org/S3zjnKoD
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With