Python provides a rich set of built-in methods to manipulate and work with strings efficiently. These methods help perform common string operations such as formatting, searching, and modifying text.
Commonly Used String Methods
1. lower()
and upper()
Convert a string to lowercase or uppercase.
text = "Hello World" print(text.lower()) # Output: hello world print(text.upper()) # Output: HELLO WORLD
2. strip()
, lstrip()
, and rstrip()
Remove whitespace from the beginning and/or end of a string.
text = " Python " print(text.strip()) # Output: "Python" print(text.lstrip()) # Output: "Python " print(text.rstrip()) # Output: " Python"
3. replace()
Replace parts of a string with another string.
text = "Hello World" print(text.replace("World", "Python")) # Output: Hello Python
4. split()
and join()
Convert a string into a list or join a list into a string.
text = "apple,banana,orange" fruits = text.split(",") print(fruits) # Output: ['apple', 'banana', 'orange'] joined_text = " - ".join(fruits) print(joined_text) # Output: apple - banana - orange
5. find()
and index()
Find the position of a substring in a string.
text = "Hello World" print(text.find("World")) # Output: 6 print(text.index("World")) # Output: 6
6. startswith()
and endswith()
Check 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()
Count occurrences of a substring in a string.
text = "banana" print(text.count("a")) # Output: 3
Key Takeaways
- String methods help manipulate text efficiently.
- Methods like
replace()
,split()
, andjoin()
are useful for modifying and formatting strings. - Methods like
find()
,startswith()
, andcount()
help in searching within strings.