Master Python string slicing [:i] to create progressive cumulative substring prefix lists.
Learn how to convert minutes into seconds in Python using arithmetic multiplication and basic unit conversions.
Create a function spelling(txt) that takes a word and spells it out by progressively building a list of substring prefixes. For example, "eats" should return ["e", "ea", "eat", "eats"].
Building progressive prefixes is used in auto-complete search bars, prefix tree (trie) data structures, and type-ahead suggestions.
Use a list comprehension slicing txt[:i] over range indices:
def spelling(txt):
return [txt[:i] for i in range(1, len(txt) + 1)]
# Testing our function
print(spelling("eats")) # Output: ['e', 'ea', 'eat', 'eats']
print(spelling("bee")) # Output: ['b', 'be', 'bee']
print(spelling("happy")) # Output: ['h', 'ha', 'hap', 'happ', 'happy']
i = 1: txt[:1] extracts index 0 ("e").i = 2: txt[:2] extracts indices 0 to 1 ("ea").i = 4: txt[:4] extracts full word ("eats").range(1, len(txt)) misses the final full word! Always use len(txt) + 1 to include the complete string slice.Use txt[:i] for cumulative prefixes. Next, let's extract city facts from Python dictionaries!