Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Output All Suffixes of a String

Python Output All Suffixes of a String

Document Object Reference Manual Python3 Examples

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"

print

(

get_all_suffixes

(

s

)

)

Code analysis:

  1. get_all_suffixes(s) is a function that takes a string s as its argument.
  2. suffixes = [] Initialize an empty list to store all the suffixes.
  3. for i in range(len(s)): Iterate over every character position in the string.
  4. suffixes.append(s[i:]) Use the slice operation s[i:] Get the substring from position i to the end of the string and add it to suffixes list.
  5. return suffixes Return the list containing all suffixes.
  6. s = "hello" Define an example string.
  7. print(get_all_suffixes(s)) Call the function and print the result.

Output result:

Example

[

'hello'

,

'ello'

,

'llo'

,

'lo'

,

'o'

]

Document Object Reference Manual Python3 Examples