Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I get last 4 characters of a string in Python?
Getting the last 4 characters of a string is a common task in Python. You can achieve this using string slicing with negative indices, which count from the end of the string.
Using Negative Slicing
The slice operator [-4:] starts from the 4th character from the end and goes to the end of the string ?
text = "Thanks. I am fine" last_four = text[-4:] print(last_four)
fine
Examples with Different Strings
Here are more examples showing how negative slicing works ?
# Different string examples
word1 = "Python"
word2 = "Programming"
word3 = "Hello World"
print("Last 4 chars of 'Python':", word1[-4:])
print("Last 4 chars of 'Programming':", word2[-4:])
print("Last 4 chars of 'Hello World':", word3[-4:])
Last 4 chars of 'Python': thon Last 4 chars of 'Programming': ming Last 4 chars of 'Hello World': orld
Handling Short Strings
When the string has fewer than 4 characters, slicing returns the entire string ?
short_text = "Hi"
result = short_text[-4:]
print(f"'{short_text}' last 4 chars: '{result}'")
# Empty string case
empty = ""
result_empty = empty[-4:]
print(f"Empty string last 4 chars: '{result_empty}'")
'Hi' last 4 chars: 'Hi' Empty string last 4 chars: ''
Alternative Method Using len()
You can also use len() to calculate the starting position ?
text = "Thanks. I am fine" start_pos = len(text) - 4 last_four = text[start_pos:] print(last_four)
fine
Conclusion
Use string[-4:] to get the last 4 characters efficiently. This method handles short strings gracefully and is the most Pythonic approach for extracting characters from the end of a string.
Advertisements
