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
Check if a string is suffix of another in Python
In Python, checking if one string is a suffix of another is a common string manipulation task. A suffix is a substring that appears at the end of a string. For example, "ate" is a suffix of "unfortunate".
Python provides multiple approaches to solve this problem efficiently ?
Method 1: Using endswith() Method
The simplest approach is to use Python's built-in endswith() method ?
s = "ate"
t = "unfortunate"
result = t.endswith(s)
print(f"Is '{s}' a suffix of '{t}'? {result}")
Is 'ate' a suffix of 'unfortunate'? True
Method 2: Using String Slicing
Compare the last characters of the longer string with the shorter string ?
def is_suffix_slice(s, t):
if len(s) > len(t):
return False
return t[-len(s):] == s
s = "ate"
t = "unfortunate"
result = is_suffix_slice(s, t)
print(f"Is '{s}' a suffix of '{t}'? {result}")
# Test with non-suffix
s2 = "fun"
result2 = is_suffix_slice(s2, t)
print(f"Is '{s2}' a suffix of '{t}'? {result2}")
Is 'ate' a suffix of 'unfortunate'? True Is 'fun' a suffix of 'unfortunate'? False
Method 3: Character-by-Character Comparison
Manually compare characters from the end of both strings ?
def is_suffix_manual(s, t):
s_len = len(s)
t_len = len(t)
if s_len > t_len:
return False
for i in range(s_len):
if s[s_len - i - 1] != t[t_len - i - 1]:
return False
return True
s = "ate"
t = "unfortunate"
result = is_suffix_manual(s, t)
print(f"Is '{s}' a suffix of '{t}'? {result}")
# Additional test cases
test_cases = [
("ing", "programming", True),
("xyz", "hello", False),
("hello", "hi", False)
]
for suffix, string, expected in test_cases:
result = is_suffix_manual(suffix, string)
print(f"'{suffix}' suffix of '{string}': {result}")
Is 'ate' a suffix of 'unfortunate'? True 'ing' suffix of 'programming': True 'xyz' suffix of 'hello': False 'hello' suffix of 'hi': False
Comparison
| Method | Time Complexity | Readability | Best For |
|---|---|---|---|
endswith() |
O(n) | High | Most cases |
| String Slicing | O(n) | Medium | Simple logic |
| Manual Comparison | O(n) | Low | Educational purposes |
Conclusion
Use endswith() for most suffix checking tasks as it's the most readable and Pythonic approach. String slicing offers a simple alternative, while manual comparison helps understand the underlying logic.
Advertisements
