Python
All Python String Functions and Methods, CBSE Class 11 & 12 Quick Reference
Complete list of Python string methods for CBSE Class 11 and 12. Syntax, examples, and output for every string function. Slicing and formatting included.
Strings are one of the most tested topics in CBSE Computer Science exams. This guide covers every string method you need to know, with syntax, examples, and output.
Basics: What is a String?
A string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes.
s1 = 'Hello'
s2 = "World"
s3 = '''This is a
multi-line string'''
Strings in Python are immutable - once created, they cannot be changed. Every string method returns a new string and does not modify the original.
s = "hello"
s.upper() # Returns "HELLO"
print(s) # Still "hello" - original unchanged
String Indexing
Each character in a string has a position (index). Indexing starts from 0 (left) or -1 (right).
s = "PYTHON"
# P Y T H O N
# 0 1 2 3 4 5 (positive index)
# -6 -5 -4 -3 -2 -1 (negative index)
print(s[0]) # P
print(s[3]) # H
print(s[-1]) # N
print(s[-3]) # H
String Slicing
Slicing extracts a part of the string. Syntax: string[start:stop:step]
s = "COMPUTER"
print(s[0:4]) # COMP (index 0 to 3)
print(s[3:7]) # PUTE (index 3 to 6)
print(s[:4]) # COMP (start defaults to 0)
print(s[4:]) # UTER (stop defaults to end)
print(s[::2]) # CMUE (every 2nd character)
print(s[::-1]) # RETUPMOC (reverse the string)
print(s[-4:]) # UTER (last 4 characters)
print(s[1:6:2]) # OPT (index 1 to 5, step 2)
Exam tip: s[::-1] to reverse a string is asked frequently. Memorize it.
Case Conversion Methods
upper(), Convert to Uppercase
s = "hello world"
print(s.upper())
HELLO WORLD
lower(), Convert to Lowercase
s = "HELLO WORLD"
print(s.lower())
hello world
capitalize(), First Character Uppercase
s = "hello world"
print(s.capitalize())
Hello world
Only the first character of the entire string is capitalized. Everything else becomes lowercase.
title(), Title Case
s = "hello world python"
print(s.title())
Hello World Python
First character of each word is capitalized.
swapcase(), Swap Upper and Lower
s = "Hello World"
print(s.swapcase())
hELLO wORLD
Search Methods
find(), Find Position of Substring
s = "Python Programming"
print(s.find("Pro")) # 7
print(s.find("Java")) # -1 (not found)
print(s.find("P")) # 0 (first occurrence)
print(s.find("P", 1)) # 7 (search from index 1)
find() returns -1 if the substring is not found. It does NOT raise an error.
index(), Find Position of Substring
s = "Python Programming"
print(s.index("Pro")) # 7
# print(s.index("Java")) # ValueError! (raises error if not found)
index() is similar to find(), but raises a ValueError if the substring is not found.
count(), Count Occurrences
s = "banana"
print(s.count("a")) # 3
print(s.count("an")) # 2
print(s.count("z")) # 0
startswith() and endswith()
s = "Hello World"
print(s.startswith("Hello")) # True
print(s.startswith("World")) # False
print(s.endswith("World")) # True
print(s.endswith("ld")) # True
Modification Methods
replace(), Replace Substring
s = "I like Java"
print(s.replace("Java", "Python"))
I like Python
Replace all occurrences:
s = "aabbcc"
print(s.replace("a", "x")) # xxbbcc
print(s.replace("a", "x", 1)) # xabbcc (replace only first occurrence)
strip(), Remove Leading and Trailing Whitespace
s = " Hello World "
print(s.strip()) # "Hello World"
print(s.lstrip()) # "Hello World "
print(s.rstrip()) # " Hello World"
strip()removes from both sideslstrip()removes from left onlyrstrip()removes from right only
You can also strip specific characters:
s = "###Hello###"
print(s.strip("#")) # Hello
Split and Join
split(), Split String into a List
s = "Python is fun"
print(s.split()) # ['Python', 'is', 'fun']
s2 = "a,b,c,d"
print(s2.split(",")) # ['a', 'b', 'c', 'd']
s3 = "one::two::three"
print(s3.split("::")) # ['one', 'two', 'three']
By default, split() splits by whitespace (spaces, tabs, newlines).
join(), Join List into a String
words = ['Python', 'is', 'fun']
print(" ".join(words)) # Python is fun
print("-".join(words)) # Python-is-fun
print("".join(words)) # Pythonisfun
join() is the reverse of split(). The string before .join() is the separator.
Checking Methods (Return True/False)
isalpha(), Only Alphabets?
print("Hello".isalpha()) # True
print("Hello123".isalpha()) # False
print("Hello World".isalpha())# False (space is not alphabet)
isdigit(), Only Digits?
print("12345".isdigit()) # True
print("123.45".isdigit()) # False (dot is not a digit)
print("12abc".isdigit()) # False
isalnum(), Alphabets or Digits?
print("Hello123".isalnum()) # True
print("Hello 123".isalnum()) # False (space is not alnum)
print("Hello!".isalnum()) # False
isspace(), Only Whitespace?
print(" ".isspace()) # True
print(" a ".isspace()) # False
print("\t\n".isspace()) # True
isupper() and islower()
print("HELLO".isupper()) # True
print("Hello".isupper()) # False
print("hello".islower()) # True
print("Hello".islower()) # False
String Operators
Concatenation (+)
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # Hello World
Repetition (*)
s = "Ha"
print(s * 3) # HaHaHa
Membership (in, not in)
s = "Python Programming"
print("Pro" in s) # True
print("Java" in s) # False
print("Java" not in s) # True
String Formatting
Using f-strings (Recommended)
name = "Aman"
marks = 85
print(f"Student {name} scored {marks} marks")
Student Aman scored 85 marks
Using format()
print("Student {} scored {} marks".format("Aman", 85))
print("Student {0} scored {1} marks".format("Aman", 85))
Using % operator (Old style)
print("Student %s scored %d marks" % ("Aman", 85))
Built-in Functions with Strings
s = "Python"
print(len(s)) # 6 (length)
print(max(s)) # y (highest ASCII value)
print(min(s)) # P (lowest ASCII value)
print(ord("A")) # 65 (ASCII value)
print(chr(65)) # A (character from ASCII)
Common Exam Questions
Q1: Write the output:
s = "Hello World"
print(s[2:8])
print(s[-5:-2])
print(s[::3])
llo Wo
Wor
HlWl
Q2: Write the output:
s = "Python"
s1 = s.upper()
s2 = s.replace("P", "J")
print(s, s1, s2)
Python PYTHON Jython
The original string s is unchanged because strings are immutable.
Q3: Write a program to count vowels and consonants in a string.
s = input("Enter a string: ")
vowels = consonants = 0
for ch in s.lower():
if ch.isalpha():
if ch in "aeiou":
vowels += 1
else:
consonants += 1
print(f"Vowels: {vowels}, Consonants: {consonants}")
Q4: Write a program to check if a string is a palindrome.
s = input("Enter a string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
Quick Reference Table
| Method | Returns | Example | Output |
|---|---|---|---|
upper() |
Uppercase string | "hi".upper() |
"HI" |
lower() |
Lowercase string | "HI".lower() |
"hi" |
capitalize() |
First char upper | "hi there".capitalize() |
"Hi there" |
title() |
Each word capitalized | "hi there".title() |
"Hi There" |
swapcase() |
Case swapped | "Hi".swapcase() |
"hI" |
strip() |
Whitespace removed | " hi ".strip() |
"hi" |
split() |
List of words | "a b c".split() |
["a","b","c"] |
join() |
Joined string | "-".join(["a","b"]) |
"a-b" |
find() |
Index or -1 | "hello".find("ll") |
2 |
replace() |
New string | "hi".replace("h","b") |
"bi" |
count() |
Count | "aab".count("a") |
2 |
startswith() |
True/False | "hi".startswith("h") |
True |
isalpha() |
True/False | "abc".isalpha() |
True |
isdigit() |
True/False | "123".isdigit() |
True |
isalnum() |
True/False | "a1".isalnum() |
True |
Bookmark this page and use it for quick revision before your exam. Practice each method by writing the output on paper first, then verifying in Python.
Want to learn more?
Explore free chapter-wise notes with quizzes and code playground
Prefer watching over reading?
Subscribe for free.