Nearby lessons

52 of 109

Python - String Methods

📌 What You Will Learn
  • Understand how string methods are called and why they are used
  • Learn case conversion and case checking methods
  • Learn how to search, replace and count text in a string
  • Convert between strings and lists using split() and join()
  • Apply string methods in small real-world programs

What Are String Methods?

A method is a function that belongs to an object.

In Python, every string has a built-in set of methods that we can call using dot notation: text.method(arguments)

Important: String methods never modify the original string. They return a new string, because strings are immutable.

1. upper() and lower()

upper() converts all characters to uppercase, and lower() converts all characters to lowercase.

🐍Code Cell
1text = "Hello Python"
2print(text.upper())
3print(text.lower())
Output
HELLO PYTHON
hello python

2. title() and capitalize()

title() capitalizes the first letter of every word, while capitalize() capitalizes only the first letter of the string.

🐍Code Cell
1text = "welcome to python"
2print(text.title())
3print(text.capitalize())
Output
Welcome To Python
Welcome to python

3. swapcase()

swapcase() converts uppercase letters to lowercase and lowercase letters to uppercase.

🐍Code Cell
1text = "Hello PYTHON"
2print(text.swapcase())
Output
hELLO python

4. isupper() and islower()

isupper() returns True if all characters are uppercase. islower() returns True if all characters are lowercase.

🐍Code Cell
1print("HELLO".isupper())
2print("hello".islower())
3print("Hello".isupper())
Output
True
True
False

5. istitle()

istitle() returns True if every word starts with an uppercase letter.

🐍Code Cell
1print("Welcome To Python".istitle())
2print("Welcome to python".istitle())
Output
True
False

6. isalpha() and isdigit()

isalpha() returns True if the string contains only letters. isdigit() returns True if the string contains only digits.

🐍Code Cell
1print("python".isalpha())
2print("python123".isalpha())
3print("12345".isdigit())
4print("12a45".isdigit())
Output
True
False
True
False

7. isalnum()

isalnum() returns True if the string contains only letters and digits (no spaces or symbols).

🐍Code Cell
1print("python123".isalnum())
2print("python 123".isalnum())
Output
True
False

8. isspace()

isspace() returns True if the string contains only whitespace characters.

🐍Code Cell
1print(" ".isspace())
2print(" a ".isspace())
Output
True
False

9. strip()

strip() removes leading and trailing spaces from a string.

🐍Code Cell
1text = " Hello Python "
2print(text.strip())
Output
Hello Python

10. lstrip() and rstrip()

lstrip() removes only the left (leading) spaces, and rstrip() removes only the right (trailing) spaces.

🐍Code Cell
1text = " Hello Python "
2print("[" + text.lstrip() + "]")
3print("[" + text.rstrip() + "]")
Output
[Hello Python   ]
[   Hello Python]

11. strip() with a Character Argument

We can pass characters to strip() to remove them from both ends of the string.

🐍Code Cell
1text = "xxxHello Pythonxxx"
2print(text.strip("x"))
Output
Hello Python

12. find() and rfind()

find() returns the index of the first occurrence of a substring. rfind() returns the index of the last occurrence.

🐍Code Cell
1text = "Python is easy to learn, Python is fun"
2print(text.find("Python"))
3print(text.rfind("Python"))
Output
0
25

13. find() When the Substring Is Not Present

If the substring is not found, find() returns -1.

🐍Code Cell
1text = "Hello Python"
2print(text.find("Java"))
Output
-1

14. index() and rindex()

index() and rindex() work like find() and rfind(), but they raise a ValueError if the substring is not found.

🐍Code Cell
1text = "Python Python"
2print(text.index("Python"))
3print(text.rindex("Python"))
Output
0
7

15. count()

count() returns how many times a substring appears in the string.

🐍Code Cell
1text = "Python is easy. Python is fun."
2print(text.count("Python"))
3print(text.count("is"))
Output
2
2

16. replace()

replace() replaces all occurrences of a substring with another substring. A third argument limits how many replacements are made.

🐍Code Cell
1text = "I love Python and Python is easy"
2print(text.replace("Python", "Java"))
3print(text.replace("Python", "Java", 1))
Output
I love Java and Java is easy
I love Java and Python is easy

17. split()

split() divides a string into a list of words. By default, it splits on spaces.

🐍Code Cell
1text = "Python is easy"
2print(text.split())
Output
['Python', 'is', 'easy']

18. split() with maxsplit

We can pass a separator and a maximum number of splits.

🐍Code Cell
1text = "Python is easy to learn"
2print(text.split(" ", 2))
Output
['Python', 'is', 'easy to learn']

19. splitlines()

splitlines() splits a multi-line string into a list of lines.

🐍Code Cell
1text = "line1\nline2\nline3"
2print(text.splitlines())
Output
['line1', 'line2', 'line3']

20. join()

join() is the opposite of split(). It joins a list of strings into one string using a separator.

🐍Code Cell
1words = ["Python", "is", "easy"]
2print(" ".join(words))
3print("-".join(words))
Output
Python is easy
Python-is-easy

21. startswith() and endswith()

startswith() checks whether the string begins with a given substring. endswith() checks whether it ends with a given substring.

🐍Code Cell
1text = "python-programming"
2print(text.startswith("python"))
3print(text.startswith("Python"))
4print(text.endswith("programming"))
Output
True
False
True

22. center(), ljust() and rjust()

These methods pad the string to a given width. center() places the string in the middle, ljust() on the left, and rjust() on the right.

🐍Code Cell
1text = "Python"
2print(text.center(11, "*"))
3print(text.ljust(11, "-"))
4print(text.rjust(11, "."))
Output
***Python**
Python-----
.....Python

23. zfill()

zfill() pads the string with zeros on the left until it reaches the given width.

🐍Code Cell
1num = "42"
2print(num.zfill(5))
Output
00042

24. Program - Reverse a String

Using slicing, we can reverse a string in one line.

🐍Code Cell
1text = "Python"
2print(text[::-1])
Output
nohtyP

25. Program - Reverse the Words of a Sentence

Split the sentence into words, reverse the list, and join it back.

🐍Code Cell
1sentence = "Python is easy"
2words = sentence.split()
3reversed_words = " ".join(words[::-1])
4print(reversed_words)
Output
easy is Python

26. Program - Count the Vowels

Loop through the string and count every vowel using the in operator.

🐍Code Cell
1text = "Hello World"
2count = 0
3for ch in text.lower():
4 if ch in "aeiou":
5 count += 1
6print(count)
Output
3

27. Program - Check if a Word Is a Palindrome

A palindrome reads the same forwards and backwards.

🐍Code Cell
1text = "madam"
2print(text == text[::-1])
Output
True
📝 Key Takeaways
  • String methods are called with dot notation: text.method()
  • String methods never modify the original string - they return a new string
  • Use find() / index() to search, replace() to substitute, split() / join() to convert between strings and lists
  • Methods like isupper(), isdigit() and isalpha() return True or False
  • String methods are case-sensitive, so text.find('Python') and text.find('python') are different

🧠 Test Your Knowledge

8 Questions

Progress: 0 / 8