In this video, we delve into how to use Python string methods to process text. You’ll learn how to remove leading and trailing whitespace from strings, convert strings to lowercase and uppercase, replace substrings, and split strings using a specified separator. We will demonstrate each method step-by-step with specific code examples, helping you easily master these common string operation techniques.
1. Video.
2. Python Source Code.
# strip() method removes any leading and trailing whitespaces def strip_example(): # Define a string with leading and trailing whitespaces a = " Good Morning! " # Remove leading and trailing whitespaces stripped = a.strip() print(stripped) # Output: "Good Morning!" # lower() method returns the string in lowercase def lower_example(): # Define a string with uppercase characters a = "GOOD EVENING!" # Convert to lowercase lowercased = a.lower() print(lowercased) # Output: "good evening!" # upper() method returns the string in uppercase def upper_example(): # Define a string with lowercase characters a = "good night!" # Convert to uppercase uppercased = a.upper() print(uppercased) # Output: "GOOD NIGHT!" # replace() method replaces a substring with another substring def replace_example(): # Define a string a = "I love Python!" # Replace "love" with "like" replaced = a.replace("love", "like") print(replaced) # Output: "I like Python!" # split() method splits the string at the specified separator def split_example(): # Define a string with a space separator a = "Python is fun" # Split the string by space splitted = a.split(" ") print(splitted) # Output: ['Python', 'is', 'fun'] # Main function def main(): strip_example() lower_example() upper_example() replace_example() split_example() # Call the main function if __name__ == "__main__": main()