I have the following string: "aaaabbbb"
How can I get the last four characters and store them in a string using Python?
Anders
7,9479 gold badges50 silver badges80 bronze badges
asked Nov 2, 2011 at 16:27
0
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.
answered Nov 2, 2011 at 16:29
ConstantiniusConstantinius
33k7 gold badges74 silver badges84 bronze badges
3
Not the answer you're looking for? Browse other questions tagged python string or ask your own question.
In this tutorial, we are going to learn about how to get the last n characters of a string in Python.
Consider, we have the following string:
Getting the last n characters
To access the last n characters of a string in Python, we can use the subscript syntax [ ]
by passing -n:
as an argument to it.
-n
is the number of characters we need to extract from the end position of a string.
Here is an example, that gets the last 4 characters from a string.
str = "abcdef"
lastFour = str[-4:] # getting the last 4 characters
print[lastFour]
Output:
You can also read, how to get first n characters of a string in Python.
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Given a string and an integer N, the task is to write a python program to print the last N characters of the string.
Example:
Input: Geeks For Geeks!; N = 4
Output: eks!
Explanation: The given string is Geeks For Geeks! and the last 4 characters is eks!.
Input: PYTHON; N=1
Output: N
Explanation: The given string is PYTHON and the last character is N.
Method 1: Using a loop to get to the last N characters of the given string.
Python3
Str
=
"Geeks For Geeks!"
N
=
4
print
[
Str
]
while
[N >
0
]:
print
[
Str
[
-
N], end
=
'']
N
=
N
-
1
Output:
Geeks For Geeks! eks!
Time Complexity:O[n]
Auxiliary Space: O[n]
Method 2: Using list slicing to print the last n characters of the given string.
Python
Str
=
"Geeks For Geeks!"
N
=
4
print
[
Str
]
length
=
len
[
Str
]
Str2
=
Str
[length
-
N:]
print
[Str2]
Output:
Geeks For Geeks! eks!
Time Complexity: O[k]
Auxiliary Space: O[n]