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

Python Get All Prefixes of a String

Python Get All Prefixes of a String

Document Object Reference Manual Python3 Examples

In Python, we can get all prefixes of a string with a simple loop. A prefix is a substring from the beginning of the string to any position. For example, all the prefixes of "hello" are "h", "he", "hel", "hell", "hello".

Example

def

get_all_prefixes

(

s

)

:

    prefixes

=

[

]

   

for

i

in

range

(

1

,

len

(

s

)

1

)

:

        prefixes.

append

(

s

[

:i

]

)

   

return

prefixes

Example

s

=

"hello"

print

(

get_all_prefixes

(

s

)

)

Code analysis:

  1. get_all_prefixes(s) is a function that takes a string s as its argument.
  2. prefixes = [] Initialize an empty list to store all the prefixes.
  3. for i in range(1, len(s) + 1) The loop runs from 1 to the length of the string plus 1, which ensures we get all possible prefixes.
  4. prefixes.append(s[:i]) Add the first s 's first i characters of the string as a prefix to prefixes list.
  5. return prefixes Return the list containing all prefixes.
  6. In the example we call this function with the string "hello" and print the result.

Output result:

Example

[

'h'

,

'he'

,

'hel'

,

'hell'

,

'hello'

]

Document Object Reference Manual Python3 Examples