Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

String Methods

Python provides a wide range of built-in methods to manipulate and work with strings effectively. These methods help in modifying, searching, and analyzing string data with ease.

Common String Methods

1. upper() and lower()

  • Converts the entire string to uppercase or lowercase.
    text = "Hello, World!"
    print(text.upper())  # Output: "HELLO, WORLD!"
    print(text.lower())  # Output: "hello, world!"

2. strip(), lstrip(), and rstrip()

  • Removes leading and trailing whitespace characters (or specific characters).
    text = "  Hello, World!  "
    print(text.strip())   # Output: "Hello, World!"
    print(text.lstrip())  # Output: "Hello, World!  "
    print(text.rstrip())  # Output: "  Hello, World!"

3. replace()

  • Replaces occurrences of a substring with another substring.
    text = "Hello, World!"
    print(text.replace("World", "Python"))  # Output: "Hello, Python!"

4. split() and join()

  • split() breaks a string into a list based on a delimiter.
  • join() combines elements of a list into a single string using a delimiter.
    
    text = "apple,banana,orange"
    words = text.split(",")
    print(words)  # Output: ['apple', 'banana', 'orange']

new_text = "-".join(words) print(new_text) # Output: "apple-banana-orange"


### 5. `find()` and `index()`
- `find()` searches for a substring and returns its index (or -1 if not found).
- `index()` is similar but raises an error if the substring is not found.
```python
text = "Hello, World!"
print(text.find("World"))  # Output: 7
print(text.index("World"))  # Output: 7

6. startswith() and endswith()

  • Checks if a string starts or ends with a specific substring.
    text = "Python programming"
    print(text.startswith("Python"))  # Output: True
    print(text.endswith("ing"))  # Output: True

7. count()

  • Counts occurrences of a substring.
    text = "banana banana banana"
    print(text.count("banana"))  # Output: 3

8. capitalize() and title()

  • capitalize(): Capitalizes the first letter of the string.
  • title(): Capitalizes the first letter of every word.
    text = "hello world"
    print(text.capitalize())  # Output: "Hello world"
    print(text.title())  # Output: "Hello World"

Exercise: Try It Yourself!

  1. Write a Python program that takes a user’s full name as input and:

    • Converts it to uppercase.
    • Removes any extra spaces.
    • Checks if the name starts with "A".
  2. Given the string "The quick brown fox jumps over the lazy dog", perform the following:

    • Count how many times "o" appears.
    • Replace "quick" with "slow".
    • Convert the entire string to title case.

Try these exercises in your Python environment and explore different string methods!