String Methods
Python provides a variety of built-in string methods that allow you to perform various operations on strings.
1. capitalize()
Converts the first character of the string to uppercase and the rest to lowercase.
text = "hello world"
capitalized_text = text.capitalize() # 'Hello world'
2. upper()
and lower()
upper()
: Converts all characters in the string to uppercase.
lower()
: Converts all characters in the string to lowercase.
text = "Hello World"
upper_case = text.upper() # 'HELLO WORLD'
lower_case = text.lower() # 'hello world'
3. title()
Converts the first character of each word to uppercase.
text = "python programming"
title_case = text.title() # 'Python Programming'
4. len()
Returns the length (number of characters) of the string.
text = "Python"
length = len(text) # 6
5. strip()
, lstrip()
, rstrip()
strip()
: Removes leading and trailing whitespaces.
lstrip()
: Removes leading whitespaces.
rstrip()
: Removes trailing whitespaces.
spaced_text = " Python "
stripped_text = spaced_text.strip() # 'Python'
left_stripped = spaced_text.lstrip() # 'Python '
right_stripped = spaced_text.rstrip() # ' Python'
6. replace(old, new)
Replaces occurrences of the specified substring with another substring.
sentence = "I love programming in Python."
new_sentence = sentence.replace("Python", "JavaScript")
7. find(substring)
and index(substring)
find(substring)
: Returns the index of the first occurrence of the substring (or -1 if not found).
index(substring)
: Returns the index of the first occurrence of the substring (raises an error if not found).
sentence = "Python is easy to learn."
index_of_easy = sentence.find("easy") # 10
index_of_java = sentence.find("Java") # -1
8. count(substring)
Returns the number of occurrences of a substring in the string.
sentence = "Python programming is fun and Python is easy to learn."
count_python = sentence.count("Python") # 2
9. startswith(prefix)
and endswith(suffix)
startswith(prefix)
: Returns True
if the string starts with the specified prefix.
endswith(suffix)
: Returns True
if the string ends with the specified suffix.
filename = "example.txt"
starts_with = filename.startswith("example") # True
ends_with = filename.endswith(".txt") # True
10. split(separator)
Splits the string into a list of substrings based on the specified separator.
sentence = "Python is easy to learn."
words = sentence.split() # ['Python', 'is', 'easy', 'to', 'learn.']
These are just a few examples of the many string methods available in Python. Understanding and using these methods can greatly simplify string manipulation tasks in your programs.