Working with String Methods
String methods are built-in functions that perform useful tasks on strings.
Case Modification
| Method | Description | Example |
|---|---|---|
.lower() | Converts all characters to lowercase. | 'Hello'.lower() -> 'hello' |
.upper() | Converts all characters to uppercase. | 'Hello'.upper() -> 'HELLO' |
.capitalize() | Converts the first character to uppercase and the rest to lowercase. | 'python code'.capitalize() -> 'Python code' |
.title() | Converts the first character of every word to uppercase. | 'hello world'.title() -> 'Hello World' |
Removing Whitespace (.strip())
Whitespace often causes issues when dealing with user input. .strip() removes leading and trailing whitespace (spaces, tabs, newlines).
python user_input = ' username@email.com \n' clean_input = user_input.strip() print(f'Original: "{user_input}"') print(f'Stripped: "{clean_input}"')
Other variations:
leading = ' Hello World'.lstrip() # Removes leading only trailing = 'Hello World '.rstrip() # Removes trailing only