Because of this, you can do things things like the following:
Part of what makes things Python so cool is its consistency. Because strings are sequences, you already have slicing syntax to do what "substring" would do in other languages. Because of this, there is no explicit substring method on string objects.
# Slicing... hello = 'Hello, World!' # Slice Hello print(hello[:5]) # To L with it... print(hello[2:4]) print(hello[7:])
Hello ll World!
# Can combine with other string functions to do substring. # Extract the world... world_loc = hello.index("W") world_len = len("World") hello[world_loc : world_loc + world_len]
But remember, strings are immutable, so you can't use this technique to set parts of a string as you can with a list.
# This works fine: pets = ['dog', 'cat', 'chicken'] pets = 'hamster' pets
['dog', 'cat', 'hamster']
# Bit it won't work on strings: mistake = 'ABzD' # This DOES NOT work: # mistake = 'C' # Do this instead corrected = mistake.replace('z', 'C') corrected
One of the great things about sequences is you can iterate them with a loop simply:
from collections import Counter as Counter twister = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" count = Counter() for ch in twister: count[ch] += 1 count.most_common(4)
[(' ', 12), ('o', 11), ('c', 10), ('u', 7)]
But in some cases you may not even need to do that much work!
twister2 = "She sells seashells by the sea shore" # Can convert to a list letters = list(twister2) # Count the list elements Counter(letters).most_common(4) # Or more concisely Counter(list(twister2)).most_common(4)
[('e', 7), ('s', 7), (' ', 6), ('h', 4)]