Python Output All Suffixes of a String
In Python, we can get all suffixes of a string with a slice operation. A suffix of a string is the substring from some position to the end of the string. We can get all possible suffixes by iterating over every character position in the string.
Example
def
get_all_suffixes
(
s
)
:
suffixes
=
[
]
for
i
in
range
(
len
(
s
)
)
:
suffixes.
append
(
s
[
i:
]
)
return
suffixes
Example string
s
=
"hello"
(
get_all_suffixes
(
s
)
)
Code analysis:
get_all_suffixes(s)is a function that takes a stringsas its argument.suffixes = []Initialize an empty list to store all the suffixes.for i in range(len(s)):Iterate over every character position in the string.suffixes.append(s[i:])Use the slice operations[i:]Get the substring from positionito the end of the string and add it tosuffixeslist.return suffixesReturn the list containing all suffixes.s = "hello"Define an example string.print(get_all_suffixes(s))Call the function and print the result.
Output result:
Example
[
'hello'
,
'ello'
,
'llo'
,
'lo'
,
'o'
]
Python3 Examples