Python Get All Prefixes of a String
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"
(
get_all_prefixes
(
s
)
)
Code analysis:
get_all_prefixes(s)is a function that takes a stringsas its argument.prefixes = []Initialize an empty list to store all the prefixes.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.prefixes.append(s[:i])Add the firsts's firsticharacters of the string as a prefix toprefixeslist.return prefixesReturn the list containing all prefixes.- In the example we call this function with the string "hello" and print the result.
Output result:
Example
[
'h'
,
'he'
,
'hel'
,
'hell'
,
'hello'
]
Python3 Examples