|
| 1 | + |
| 2 | +# Example of string methods |
| 3 | + |
| 4 | +# Initial string |
| 5 | +text = " Hello World Python " |
| 6 | + |
| 7 | +# Convert to lowercase |
| 8 | +print(text.lower()) # Output: " hello world python " |
| 9 | + |
| 10 | +# Convert to uppercase |
| 11 | +print(text.upper()) # Output: " HELLO WORLD PYTHON " |
| 12 | + |
| 13 | +# Capitalize each word |
| 14 | +print(text.title()) # Output: " Hello World Python " |
| 15 | + |
| 16 | +# Strip leading and trailing spaces |
| 17 | +print(text.strip()) # Output: "Hello World Python" |
| 18 | + |
| 19 | +# Replace 'Python' with 'Programming' |
| 20 | +print(text.replace("Python", "Programming")) # Output: " Hello World Programming " |
| 21 | + |
| 22 | +# Split the string into a list of words |
| 23 | +print(text.split()) # Output: ['Hello', 'World', 'Python'] |
| 24 | + |
| 25 | +# Join a list of words into a single string with spaces |
| 26 | +words = ['Hello', 'World', 'Python'] |
| 27 | +print(" ".join(words)) # Output: "Hello World Python" |
| 28 | + |
| 29 | +# Find the position of 'World' |
| 30 | +print(text.find("World")) # Output: 11 |
| 31 | + |
| 32 | +# Check if the string starts with ' Hello' |
| 33 | +print(text.startswith(" Hello")) # Output: True |
| 34 | + |
| 35 | +# Check if the string ends with 'Python' |
| 36 | +print(text.endswith("Python ")) # Output: True |
| 37 | + |
| 38 | +# Check if the string contains only digits |
| 39 | +print("12345".isdigit()) # Output: True |
| 40 | + |
| 41 | +# Check if the string contains only alphabetic characters |
| 42 | +print("Hello".isalpha()) # Output: True |
| 43 | + |
| 44 | +### Key Points |
| 45 | + |
| 46 | +# - **Strings are immutable:** Methods that modify a string return a new string rather than changing the original string. |
| 47 | +# - **Method chaining:** You can chain methods together for more complex operations. For example, `text.strip().upper().replace("WORLD", "EVERYONE")`. |
| 48 | + |
0 commit comments