Python Get All Prefixes of a String
In Python, we can obtain 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 prefixes of the string "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))
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:
get_all_prefixes(s)is a function that takes a stringsas a parameter.prefixes = []Initialize an empty list to store all prefixes.for i in range(1, len(s) + 1)Loop from 1 to the length of the string plus 1, this ensures we get all possible prefixes.prefixes.append(s[:i])Add the stringsthe firsticharacters as a prefix to theprefixeslist.return prefixesReturn the list containing all prefixes.- In the example, we use the string "hello" to call this function and print the result.
Output result:
Example
['h', 'he', 'hel', 'hell', 'hello']
Python3 Examples