⚡0 XP🔥0

String Methods

Lesson 14 of 33 ⏱ 4 min read ✎ 4 exercises ❓ 6-question quiz ▶ Runs Python

The most useful string methods - case conversion, strip, split, join, replace, find, count, startswith, checks like isdigit, and formatting.

What is a method?#

A method is a function that belongs to an object. You call it with a dot: text.upper(). Python strings come with dozens of built-in methods.

Common Mistake

Strings are immutable, so string methods never change the original string - they return a new one. Always store the result:

name = "ravi"
name.upper()          # result thrown away
print(name)           # ravi
name = name.upper()   # store it
print(name)           # RAVI

Changing case#

Method Result for "hello World"
upper() HELLO WORLD
lower() hello world
title() Hello World
capitalize() Hello world
swapcase() HELLO wORLD
▶ Try it YourselfPython
Ctrl + Enter to run
Tip

Use .lower() before comparing user input: if answer.lower() == "yes": accepts "Yes", "YES" and "yes".

Removing spaces: strip, lstrip, rstrip#

Users often type extra spaces. These methods remove whitespace (spaces, tabs, newlines) from the ends:

▶ Try it YourselfPython
Ctrl + Enter to run

Splitting and joining#

split() - string → list#

▶ Try it YourselfPython
Ctrl + Enter to run

join() - list → string#

separator.join(list_of_strings):

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

split() एक string को टुकड़ों में तोड़कर list बनाता है। "Ravi,21,Indore".split(",") → ['Ravi', '21', 'Indore']

join() इसका उल्टा है - list के टुकड़ों को जोड़कर string बनाता है। इसमें जोड़ने वाला निशान (separator) पहले लिखा जाता है: "-".join(['25', '11', '2026']) → "25-11-2026"

याद रखने का तरीका: "separator.join(list)" - यानी "इस निशान से इन सबको जोड़ो"।

Common Mistake

join() works only on strings. ", ".join([1, 2, 3]) raises TypeError. Convert first: ", ".join(str(n) for n in [1, 2, 3]) (or use map(str, ...)).

Searching#

Method Purpose "banana" example
find(x) index of first x, or -1 find("an") → 1
rfind(x) index of last x, or -1 rfind("an") → 3
index(x) like find, but ValueError if missing index("z") → error
count(x) how many times x appears count("a") → 3
startswith(x) begins with x? startswith("ba") → True
endswith(x) ends with x? endswith(".pdf") → False
▶ Try it YourselfPython
Ctrl + Enter to run

Replacing#

▶ Try it YourselfPython
Ctrl + Enter to run

Checking the content (is... methods)#

These return True or False:

Method True when... Example
isdigit() all characters are digits "2026".isdigit()
isalpha() all are letters "Ravi".isalpha()
isalnum() letters or digits only "Room42".isalnum()
isspace() only whitespace " ".isspace()
isupper() / islower() all letters upper / lower case "ABC".isupper()
▶ Try it YourselfPython
Ctrl + Enter to run

Alignment and padding#

▶ Try it YourselfPython
Ctrl + Enter to run

Putting it together: a password validator#

▶ Try it YourselfPython
Ctrl + Enter to run

(any() returns True if at least one item is True - you'll see this pattern again with comprehensions.)

Quick reference#

Task Code
Remove spaces at ends s.strip()
Lower case s.lower()
Words list s.split()
List → text " ".join(words)
Replace text s.replace(old, new)
Position of text s.find(x)
Count text s.count(x)
Is it a number? s.isdigit()

Summary#

  • String methods return new strings - store the result.
  • Clean input with strip() and lower().
  • split() turns text into a list; sep.join(list) turns a list into text.
  • Search with find, count, startswith, endswith; edit with replace.
  • Validate with isdigit, isalpha, isalnum.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Clean a name

The input has extra spaces and mixed case, like rAHUL sHaRmA. Print it cleaned in title case: Rahul Sharma

Test input:
   rAHUL   sHaRmA  
Expected output:
Rahul Sharma
2

Word count

Read a sentence and print the number of words in it.

Test input:
Python is easy to learn and fun to use
Expected output:
9
3

Email username and domain

Read an email address and print the username and the domain on separate lines. For ravi.k@vindhyaedu.com:

Username: ravi.k
Domain: vindhyaedu.com
Test input:
ravi.k@vindhyaedu.com
Expected output:
Username: ravi.k
Domain: vindhyaedu.com
4

Character frequency

Read a word and a single character (two lines). Print how many times that character appears in the word, ignoring case.

Test input:
Mississippi
S
Expected output:
4

Quick Quiz

Q1.

What is " hello ".strip()?

Q2.

What is "a,b,c".split(",")?

Q3.

What is "-".join(["2026", "11", "25"])?

Q4.

What does "banana".find("z") return?

Q5.

Does s.upper() change the string s?

Q6.

What is "12a".isdigit()?