Python Get All Prefixes of a String

Document 对象参考手册Python3 Examples

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))

Code analysis:

  1. get_all_prefixes(s)is a function that takes a stringsas a parameter.
  2. prefixes = []Initialize an empty list to store all prefixes.
  3. 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.
  4. prefixes.append(s[:i])Add the stringsthe firsticharacters as a prefix to theprefixeslist.
  5. return prefixesReturn the list containing all prefixes.
  6. In the example, we use the string "hello" to call this function and print the result.

Output result:

Example

['h', 'he', 'hel', 'hell', 'hello']

Document 对象参考手册Python3 Examples

Other extensions