Strings have many built-in methods for common tasks. These methods return new strings and do not change the original.
Basic methods for changing case
text = "hello python"
print(text.upper()) # HELLO PYTHON
print(text.lower()) # hello python
print(text.title()) # Hello Python
print(text.capitalize()) # Hello python
Removing whitespace
messy = " hello "
print(messy.strip()) # "hello"
print(messy.lstrip()) # "hello "
print(messy.rstrip()) # " hello"
Finding and replacing
sentence = "I like cats and cats like me"
print(sentence.find("cats")) # 7 (first position)
print(sentence.replace("cats", "dogs")) # I like dogs and dogs like me
Checking content
email = "user@example.com"
print(email.startswith("user")) # True
print(email.endswith(".com")) # True
print("123".isdigit()) # True
print("abc".isalpha()) # True
Splitting and joining
words = "apple,banana,cherry"
word_list = words.split(",")
print(word_list) # ['apple', 'banana', 'cherry']
new_string = "-".join(word_list)
print(new_string) # apple-banana-cherry
Simple examples
Clean user input:
name = " Alice "
clean_name = name.strip().title()
print(clean_name) # Alice
Count occurrences (use count method):
text = "hello hello world"
print(text.count("hello")) # 2
Quick summary
- Methods like
.upper(),.lower(),.strip()for formatting. -
.find(),.replace()for searching and changing. -
.startswith(),.endswith(),.isdigit()for checks. -
.split()and.join()for lists and strings.
Practice common string methods on text. They are essential for cleaning and processing strings in Python programs.
Top comments (0)