Advanced Strings
Working with strings in Python: indexing, slicing, splitting and joining, escaping, stripping, membership tests, and formatting.
Indexing, Slicing, Splitting
my_name = "Jake"
print(my_name[0]) # prints "J"
print(my_name[-1]) # prints "e"
sentence = "This is a sentence."
print(sentence[:4]) # prints "This"
sentence_split = sentence.split()
sentence_join = ' '.join(sentence_split)
print(sentence_join)
Escaping Characters
string1 = "He said, 'Give me all your money'"
string2 = "He said, \"Give me all your money\"" # character escaping requires a \ in front of characters to escape.
Stripping Whitespace
too_much_space = " test "
print(too_much_space.strip()) # removes spacing
Membership and Case
letter = "A"
word = "Apple"
print("A" in "Apple") # True
print("a" in "Apple") # False -- lowercase doesn't match due to case sensitivity
print(letter.lower() in word.lower()) # improved solution for mixed character case
Formatting
movie = "The Hangover"
print("My favorite movie is {}.".format(movie)) # string format method
print("My favorite is %s." % movie) # percent format method
print(f"My favorite movie is {movie}.") # String literal or "f" string