String Data Type in python Class 11 Notes

Last updated on July 8th, 2026 at 08:18 am

String data type in Python 

Welcome to the complete String Data Type in Python — Class 11 Notes. Strings are one of the most important data types in Python and one of the most frequently tested topics in CBSE board exams. Every year you will find at least 2–3 questions on string indexing, slicing, and methods. These notes cover the complete CBSE syllabus — all string operations, traversal using loops, and every built-in method — with syntax, examples, and exam questions.

💡 Exam tip: String slicing and output-tracing questions appear in almost every CBSE Class 11 CS board paper. Try every code example yourself in Python IDLE or the online Python compiler — typing code is the fastest way to master it.

Quick Overview — What You Will Learn

#TopicKey ConceptsExam Weight
1Introduction to StringsDefinition, creation, immutability⭐⭐
2String IndexingPositive index, negative index, IndexError⭐⭐⭐
3String OperationsConcatenation, Repetition, Membership, Slicing⭐⭐⭐
4Traversing a Stringfor loop, while loop⭐⭐
5len()Length of string⭐⭐
6Case Methodscapitalize, title, lower, upper⭐⭐
7Search Methodscount, find, index, startswith, endswith⭐⭐⭐
8Checking Methodsisalnum, isalpha, isdigit, islower, isupper, isspace⭐⭐⭐
9Strip Methodslstrip, rstrip, strip⭐⭐
10Modify/Split Methodsreplace, join, partition, split⭐⭐⭐

Section 1Introduction ⭐⭐

💬 What is a String in Python?

A string in Python is an ordered, immutable sequence of characters — letters, digits, spaces, punctuation, or any symbol — enclosed within quotation marks. Every piece of text in Python is stored as a string.
OrderedImmutableSequencestr type

Ways to Create a String

EXAMPLES # 1. Single quotes s1 = ‘Hello’# 2. Double quotes s2 = “Hello”# 3. Triple single quotes — multi-line s3 = ”’This is a multi-line string”’# 4. Triple double quotes — multi-line s4 = “””This is also a multi-line string”””# When to use which: s5 = “It’s a beautiful day” # double quotes when string has apostrophe s6 = ‘He said “Hello”‘ # single quotes when string has double quotes

String Immutability

Strings in Python are immutable — once created, individual characters cannot be changed. Trying to do so raises a TypeError. All string methods return a new string — the original is never modified.
EXAMPLE s = “Hello” s[0] = “h” # TypeError: ‘str’ object does not support item assignment# Correct way — create a new string s = “h” + s[1:] print(s) # hello
💡 Why immutability matters for exams:
  • “Are strings mutable or immutable in Python?” is a very common 1-mark board question.
  • It explains why all string methods return a new string instead of modifying the original.
  • The original string is unchanged even after calling methods like upper() or replace().

Section 2Indexing ⭐⭐⭐

🔢 String Indexing — Accessing Individual Characters

A string is a sequence — each character has a fixed position called an index. Python supports both positive indexing (left to right, starting at 0) and negative indexing (right to left, starting at -1).
String : P Y T H O N +Index : 0 1 2 3 4 5 -Index : -6 -5 -4 -3 -2 -1EXAMPLES s = “PYTHON”# Positive indexing print(s[0]) # P print(s[1]) # Y print(s[5]) # N (last character)# Negative indexing print(s[-1]) # N (last character) print(s[-2]) # O (second from last) print(s[-6]) # P (same as s[0])# IndexError — accessing out-of-range index print(s[10]) # IndexError: string index out of range
Formula: negative_index = positive_index − len(string)
Example: For “PYTHON” (len = 6), character ‘P’ at positive index 0 has negative index 0 − 6 = −6
Positive Index starts at 0Negative Index starts at -1IndexError if out of range

Section 3String Operations ⭐⭐⭐

⚙️ String Operations

CBSE syllabus defines four string operations — concatenation, repetition, membership, and slicing. These are the most tested operations in board exams.

1. Concatenation ( + )

The + operator joins two or more strings to form a new, longer string. Both operands must be strings — you cannot concatenate a string and a number directly.
EXAMPLES s1 = “Hello” s2 = ” World” print(s1 + s2) # Hello World print(“CBSE” + ” “ + “Python”) # CBSE Python# Cannot join string + number directly print(“Age: “ + 16) # TypeError! print(“Age: “ + str(16)) # Age: 16 ✓
+ operatorBoth operands must be strCreates new string

2. Repetition ( * )

The * operator repeats a string a specified number of times. The number can be on either side of the operator.
EXAMPLES s = “Ha” print(s * 3) # HaHaHa print(3 * “Hi”) # HiHiHi print(“=” * 20) # ==================== print(“-“ * 10) # ———-
* operatorNumber on either sideCreates new string

3. Membership ( in, not in )

in returns True if a character or substring exists in the string. not in returns True if it does not. Both operators are case-sensitive.
EXAMPLES s = “Hello, Python!”print(“Python” in s) # True print(“Java” in s) # False print(“Java” not in s) # True print(“hello” in s) # False (case-sensitive!) print(“Hello” in s) # True# Common use — check vowel ch = “a” if ch in “aeiouAEIOU”: print(ch, “is a vowel”)
⚠️ in and not in are case-sensitive. "python" and "Python" are treated as completely different strings.
in operatornot in operatorCase-sensitiveReturns Boolean

4. Slicing

Slicing extracts a portion (substring) from a string. It is one of the most tested topics in CBSE board exams — almost every board paper has an output-tracing slicing question.
SYNTAX string[start : stop : step]
ParameterDefaultMeaning
start0Index where slicing begins (included)
stoplen(string)Index where slicing ends (excluded — NOT included)
step1Gap between characters. Negative step reverses direction.
EXAMPLES — study these carefully s = “PYTHON” # P Y T H O N # 0 1 2 3 4 5 # -6 -5 -4 -3 -2 -1print(s[0:3]) # PYT (index 0,1,2 — stop 3 excluded) print(s[2:5]) # THO (index 2,3,4) print(s[:3]) # PYT (start omitted — defaults to 0) print(s[3:]) # HON (stop omitted — defaults to end) print(s[:]) # PYTHON (full string copy) print(s[::2]) # PTN (every 2nd character: 0,2,4) print(s[1::2]) # YHN (from index 1, every 2nd: 1,3,5) print(s[::-1]) # NOHTYP (reverse string — most popular trick!) print(s[5:0:-1]) # NOHTY (from index 5 down to index 1)# With negative indices print(s[-4:-1]) # THO (from -4 to -2) print(s[-1:-7:-1]) # NOHTYP (reverse using negative indices)# Out-of-range — NO error (unlike indexing) print(s[0:100]) # PYTHON (Python adjusts to valid range)
Most important slicing trick for exams: s[::-1] reverses any string. Memorise this — it appears in almost every board paper.
start includedstop excludedstep default=1[::-1] reversesNo IndexError

Section 4Traversal ⭐⭐

🔄 Traversing a String Using Loops

Traversal means visiting each character of a string one by one. Python provides two ways — using a for loop (cleaner and simpler) or a while loop (when you need the index).

Using for Loop

EXAMPLE 1 — Print each character s = “Python” for ch in s: print(ch, end=” “) # Output: P y t h o nEXAMPLE 2 — Count vowels s = “Hello World” count = 0 for ch in s: if ch in “aeiouAEIOU”: count += 1 print(“Vowels:”, count) # 3EXAMPLE 3 — Print with index using range(len()) s = “CBSE” for i in range(len(s)): print(“s[“ + str(i) + “] =”, s[i])

Using while Loop

EXAMPLE 4 — Traverse forward s = “Python” i = 0 while i < len(s): print(s[i], end=” “) i += 1 # Output: P y t h o nEXAMPLE 5 — Print in reverse using while s = “Python” i = len(s) – 1 while i >= 0: print(s[i], end=“”) i -= 1 # Output: nohtyP
for ch in sfor i in range(len(s))while i < len(s)

Section 5Built-in Function ⭐⭐

📏 len() — Length of String

len(string) returns the total number of characters in the string — including spaces, digits, and special characters.
EXAMPLES print(len(“Hello, World!”)) # 13 print(len(“”)) # 0 (empty string) print(len(” “)) # 2 (spaces are counted) print(len(“Python”)) # 6# Use with loop s = “CBSE” for i in range(len(s)): print(s[i])
Section 6Case Methods ⭐⭐

🔤 Case Methods — capitalize(), title(), lower(), upper()

capitalize()

Returns a new string where the first character is uppercase and all remaining characters are lowercase.
EXAMPLES s = “hello world python” print(s.capitalize()) # Hello world pythons2 = “HELLO WORLD” print(s2.capitalize()) # Hello world (rest become lowercase!)

title()

Returns a new string where the first character of every word is uppercase and the remaining letters of each word are lowercase.
EXAMPLES s = “hello world python” print(s.title()) # Hello World Pythons2 = “cbse class 11” print(s2.title()) # Cbse Class 11
💡 capitalize() vs title() — Most Asked Difference:
  • capitalize() — only the first letter of the entire string becomes uppercase. All others lowercase.
  • title() — the first letter of every word becomes uppercase.
SIDE-BY-SIDE COMPARISON s = “hello world” print(s.capitalize()) # Hello world (only H is capital) print(s.title()) # Hello World (H and W both capital)

lower()

Returns a new string with all alphabetic characters converted to lowercase. Digits and special characters are unchanged.
EXAMPLES s = “HELLO PYTHON 123” print(s.lower()) # hello python 123# Common use — case-insensitive comparison user = input(“Enter yes or no: “) if user.lower() == “yes”: print(“You said yes!”)

upper()

Returns a new string with all alphabetic characters converted to uppercase. Digits and special characters are unchanged.
EXAMPLES s = “hello python 123” print(s.upper()) # HELLO PYTHON 123
capitalize()title()lower()upper()All return new string

Section 7Search Methods ⭐⭐⭐

🔍 Search Methods — count(), find(), index(), startswith(), endswith()

count(sub, start, end)

Returns the number of non-overlapping occurrences of a substring. Optionally search within a range [start:end].
EXAMPLES s = “Hello, Hello, Hello!” print(s.count(“Hello”)) # 3 print(s.count(“l”)) # 6s2 = “banana” print(s2.count(“a”)) # 3 print(s2.count(“a”, 2)) # 2 (count from index 2) print(s2.count(“na”)) # 2

find(sub, start, end)

Returns the lowest index where the substring is found. Returns -1 if not found — no error.
EXAMPLES s = “Hello, Python, Hello!” print(s.find(“Hello”)) # 0 (first occurrence) print(s.find(“Python”)) # 7 print(s.find(“Java”)) # -1 (not found — NO error) print(s.find(“Hello”, 5)) # 15 (search from index 5)

index(sub, start, end)

Works exactly like find() but raises a ValueError if the substring is not found.
EXAMPLES s = “Hello, Python!” print(s.index(“Python”)) # 7 print(s.index(“Hello”)) # 0 # print(s.index(“Java”)) # ValueError: substring not found
💡 find() vs index() — Most Asked Difference:
  • Both search for a substring and return its first index if found.
  • find() returns -1 if substring not found — safe to use without try-except.
  • index() raises ValueError if not found — use when you are sure the substring exists.

startswith(prefix, start, end)

Returns True if the string starts with the given prefix; otherwise False. Case-sensitive.
EXAMPLES s = “Hello, Python!” print(s.startswith(“Hello”)) # True print(s.startswith(“Python”)) # False print(s.startswith(“He”)) # True print(s.startswith(“he”)) # False (case-sensitive) print(s.startswith(“Python”, 7)) # True (check from index 7)

endswith(suffix, start, end)

Returns True if the string ends with the given suffix; otherwise False. Case-sensitive.
EXAMPLES s = “Hello, Python!” print(s.endswith(“!”)) # True print(s.endswith(“Python!”)) # True print(s.endswith(“Python”)) # False (no ! at end)# Practical use — check file extension filename = “notes.pdf” print(filename.endswith(“.pdf”)) # True print(filename.endswith(“.docx”)) # False
count()find() → -1 if not foundindex() → ValueErrorstartswith()endswith()

Section 8Checking Methods ⭐⭐⭐

✅ Checking / Validation Methods

These methods all return True or False. They are extremely useful for validating user input. Non-alphabetic characters (digits, spaces) are ignored in islower() and isupper(). All methods return False for an empty string.

isalnum()

Returns True if all characters are letters or digits (alphanumeric) and the string is not empty.
EXAMPLES print(“Hello123”.isalnum()) # True — letters and digits only print(“Hello 123”.isalnum()) # False — space not allowed print(“Hello!”.isalnum()) # False — ‘!’ not alphanumeric print(“”.isalnum()) # False — empty string

isalpha()

Returns True if all characters are alphabetic letters only (A-Z or a-z) and string is not empty.
EXAMPLES print(“Hello”.isalpha()) # True print(“Hello World”.isalpha()) # False — space not a letter print(“Hello1”.isalpha()) # False — ‘1’ not a letter

isdigit()

Returns True if all characters are digits (0-9) and string is not empty.
EXAMPLES print(“12345”.isdigit()) # True print(“123.45”.isdigit()) # False — ‘.’ not a digit print(“123 45”.isdigit()) # False — space not a digit print(“0”.isdigit()) # True

islower()

Returns True if all alphabetic characters are lowercase and there is at least one alphabetic character. Digits and spaces are ignored.
EXAMPLES print(“hello”.islower()) # True print(“hello world”.islower()) # True — space ignored print(“hello123”.islower()) # True — digits ignored print(“Hello”.islower()) # False — ‘H’ is uppercase print(“123”.islower()) # False — no alphabetic char at all

isupper()

Returns True if all alphabetic characters are uppercase and there is at least one alphabetic character. Digits and spaces are ignored.
EXAMPLES print(“HELLO”.isupper()) # True print(“HELLO WORLD”.isupper()) # True — space ignored print(“HELLO123”.isupper()) # True — digits ignored print(“Hello”.isupper()) # False — lowercase letters present print(“123”.isupper()) # False — no alphabetic char

isspace()

Returns True if all characters are whitespace — spaces, tabs (\t), newlines (\n) — and the string is not empty.
EXAMPLES print(” “.isspace()) # True — only spaces print(“\t\n”.isspace()) # True — tab and newline print(“Hello”.isspace()) # False print(“”.isspace()) # False — empty string
MethodReturns True WhenFalse For Empty String?
isalnum()All chars are letters OR digitsYes — False
isalpha()All chars are letters onlyYes — False
isdigit()All chars are digits (0-9) onlyYes — False
islower()All letters are lowercase (digits/spaces ignored)Yes — False
isupper()All letters are uppercase (digits/spaces ignored)Yes — False
isspace()All chars are whitespace (\t, \n, space)Yes — False
isalnum()isalpha()isdigit()islower()isupper()isspace()All return Boolean

Section 9Strip Methods ⭐⭐

✂️ Strip Methods — lstrip(), rstrip(), strip()

Strip methods remove unwanted characters from the ends of a string. By default they remove whitespace. If a character argument is given, they remove that specific character instead.

lstrip(chars) — Remove from Left

EXAMPLES s = ” Hello “ print(s.lstrip()) # “Hello ” (left spaces removed)s2 = “###Hello###” print(s2.lstrip(“#”)) # “Hello###” (# removed from left only)

rstrip(chars) — Remove from Right

EXAMPLES s = ” Hello “ print(s.rstrip()) # ” Hello” (right spaces removed)s2 = “Hello!!!” print(s2.rstrip(“!”)) # “Hello”

strip(chars) — Remove from Both Ends

EXAMPLES s = ” Hello “ print(s.strip()) # “Hello” (both sides cleaned)s2 = “###Hello###” print(s2.strip(“#”)) # “Hello”# Very common use — clean user input name = input(“Enter name: “) # user types ” Arjun “ clean = name.strip() # “Arjun”
MethodRemoves FromInputOutput
lstrip()Left side only”   Hello   ““Hello   “
rstrip()Right side only”   Hello   “”   Hello”
strip()Both sides”   Hello   ““Hello”
lstrip() — leftrstrip() — rightstrip() — bothDefault removes whitespace

Section 10Modify & Split Methods ⭐⭐⭐

🔧 replace(), join(), partition(), split()

replace(old, new, count)

Returns a new string where all occurrences of old are replaced by new. If count is given, only the first count occurrences are replaced.
EXAMPLES s = “Hello World! Hello Python! Hello CBSE!”print(s.replace(“Hello”, “Hi”)) # Hi World! Hi Python! Hi CBSE! print(s.replace(“Hello”, “Hi”, 1)) # Hi World! Hello Python! Hello CBSE! print(s.replace(“Hello”, “Hi”, 2)) # Hi World! Hi Python! Hello CBSE! print(s.replace(“Hello”, “”)) # effectively removes “Hello”

split(sep, maxsplit)

Splits the string into a list of substrings. Default separator is whitespace. maxsplit limits the number of splits.
EXAMPLES s = “Hello World Python” print(s.split()) # [‘Hello’, ‘World’, ‘Python’]s2 = “apple,banana,mango,grape” print(s2.split(“,”)) # [‘apple’, ‘banana’, ‘mango’, ‘grape’] print(s2.split(“,”, 2)) # [‘apple’, ‘banana’, ‘mango,grape’] (max 2 splits)# split() handles multiple spaces automatically s3 = “Hello World Python” print(s3.split()) # [‘Hello’, ‘World’, ‘Python’]# Count words sentence = “Python is easy to learn” print(“Words:”, len(sentence.split())) # Words: 5

join(iterable)

Joins all elements of a list of strings into one single string, using the calling string as the separator. Called on the separator, not on the list.
EXAMPLES words = [“Hello”, “World”, “Python”]print(” “.join(words)) # Hello World Python print(“-“.join(words)) # Hello-World-Python print(“”.join(words)) # HelloWorldPython print(“, “.join(words)) # Hello, World, Python# Reverse words in a sentence s = “Hello World Python” print(” “.join(s.split()[::-1])) # Python World Hello
⚠️ Common mistake: join() is called on the separator string — not on the list. All elements in the list must be strings. If any element is a number, you will get a TypeError.

partition(sep)

Splits the string into exactly three parts as a tuple: (part before separator, separator itself, part after separator). Splits only at the first occurrence. If separator not found, returns (full_string, ”, ”).
EXAMPLES s = “Hello, Python, World”print(s.partition(“,”)) # (‘Hello’, ‘,’, ‘ Python, World’) # before sep after (everything after first comma)print(s.partition(“Python”)) # (‘Hello, ‘, ‘Python’, ‘, World’)print(s.partition(“Java”)) # (‘Hello, Python, World’, ”, ”) — sep not found# Accessing individual parts result = s.partition(“,”) print(result[0]) # Hello (before) print(result[1]) # , (separator) print(result[2]) # ” Python, World” (after)# Practical use — split email address email = “student@cbsepython.in” user, sep, domain = email.partition(“@”) print(“User:”, user) # student print(“Domain:”, domain) # cbsepython.in
💡 partition() vs split() — Key Difference (Exam Favourite):
  • partition() always returns a tuple of exactly 3 elements — includes the separator in result.
  • split() returns a list of variable number of elements — separator is NOT in result.
  • partition() only splits at the first occurrence. split() splits at all occurrences.
SIDE-BY-SIDE COMPARISON s = “Hello,World,Python” print(s.partition(“,”)) # (‘Hello’, ‘,’, ‘World,Python’) — tuple, sep included print(s.split(“,”)) # [‘Hello’, ‘World’, ‘Python’] — list, sep excluded
replace()split() → listjoin() → stringpartition() → 3-tuple

📋 Complete Summary Table — All CBSE Syllabus String Methods

MethodWhat it DoesReturns
len(s)Total number of characters in stringInteger
capitalize()First char uppercase, rest lowercaseNew string
title()First letter of every word uppercaseNew string
lower()All characters to lowercaseNew string
upper()All characters to uppercaseNew string
count(sub)Number of times sub appears (non-overlapping)Integer
find(sub)First index of sub; -1 if not foundInteger
index(sub)First index of sub; ValueError if not foundInteger
endswith(suf)True if string ends with suffixBoolean
startswith(pre)True if string starts with prefixBoolean
isalnum()True if all chars are letters or digitsBoolean
isalpha()True if all chars are letters onlyBoolean
isdigit()True if all chars are digits onlyBoolean
islower()True if all letters are lowercaseBoolean
isupper()True if all letters are uppercaseBoolean
isspace()True if all chars are whitespaceBoolean
lstrip(ch)Removes chars from left endNew string
rstrip(ch)Removes chars from right endNew string
strip(ch)Removes chars from both endsNew string
replace(old,new)Replaces old with new (all occurrences)New string
join(list)Joins list elements into one string with separatorNew string
partition(sep)Splits into 3-tuple: (before, sep, after)Tuple of 3 strings
split(sep)Splits into list of substrings at separatorList of strings

💻 Common Programs for CBSE Practicals & Board Exams

Program 1 — Count vowels and consonants

PROGRAM s = input(“Enter a string: “) vowels = 0 consonants = 0 for ch in s: if ch.isalpha(): if ch.lower() in “aeiou”: vowels += 1 else: consonants += 1 print(“Vowels:”, vowels) print(“Consonants:”, consonants)

Program 2 — Check palindrome using slicing

PROGRAM s = input(“Enter a string: “) if s == s[::-1]: print(s, “is a Palindrome”) else: print(s, “is not a Palindrome”) # “madam” → Palindrome, “hello” → Not a Palindrome

Program 3 — Count words using split()

PROGRAM s = input(“Enter a sentence: “) words = s.split() print(“Number of words:”, len(words)) print(“Words:”) for word in words: print(word)

Program 4 — Count uppercase and lowercase letters

PROGRAM s = input(“Enter a string: “) upper = 0 lower = 0 for ch in s: if ch.isupper(): upper += 1 elif ch.islower(): lower += 1 print(“Uppercase:”, upper) print(“Lowercase:”, lower)

Program 5 — Reverse each word in a sentence

PROGRAM s = input(“Enter a sentence: “) words = s.split() for word in words: print(word[::-1], end=” “) # “Hello World” → “olleH dlroW”

Program 6 — Split email using partition()

PROGRAM email = input(“Enter email: “) user, sep, domain = email.partition(“@”) print(“Username:”, user) print(“Domain:”, domain)

Program 7 — Print only digits from a string

PROGRAM s = input(“Enter a string: “) digits = “” for ch in s: if ch.isdigit(): digits += ch print(“Digits:”, digits)

Program 8 — Remove all spaces from a string

PROGRAM s = input(“Enter a string: “) s = s.replace(” “, “”) print(“Without spaces:”, s)

Frequently Asked Questions

What is a string in Python? Is it mutable or immutable? Justify with an example.
A string is an ordered, immutable sequence of characters enclosed in quotation marks. Strings are immutable — individual characters cannot be changed after creation. Trying to do so raises a TypeError: s = "Hello"; s[0] = "h" → TypeError. To modify, create a new string: s = "h" + s[1:]
What is the difference between find() and index() in Python?
Both return the index of the first occurrence of a substring. If the substring is NOT found: find() returns -1 (no error), while index() raises a ValueError.
What is the difference between partition() and split()?
partition(sep) always returns a tuple of exactly 3 elements — (before, separator, after) — the separator is included in the result, and it splits only at the first occurrence. split(sep) returns a list of variable length — separator NOT in result — splits at all occurrences.
Example: "a,b,c".partition(",") → ('a', ',', 'b,c') vs "a,b,c".split(",") → ['a', 'b', 'c']
What is the difference between capitalize() and title()?
capitalize() makes only the first letter of the entire string uppercase (rest lowercase). title() makes the first letter of every word uppercase. Example: "hello world".capitalize() → "Hello world" vs "hello world".title() → "Hello World"
What will s[::-1] do? Why?
s[::-1] reverses the string. The step value -1 means Python starts from the last character and moves backwards one character at a time, collecting every character until the start of the string. Example: "Python"[::-1] → "nohtyP"
What is the difference between islower() returning False for “123” vs “Hello”?
islower() requires at least one alphabetic character to be present — it only checks letters, not digits or spaces. "123".islower() returns False because there are no alphabetic characters to be lowercase. "Hello".islower() returns False because ‘H’ is uppercase. "hello123".islower() returns True because all letters (‘h’,’e’,’l’,’l’,’o’) are lowercase — digits ignored.

Quick Practice Links

Explore More Class 11 CS Notes

Jitendra Singh
✔ Verified Educator

Jitendra Singh

Founder of CBSEPython.in

I help CBSE Class 9–12 students learn Python, Information Technology, Artificial Intelligence and Computer Science through easy notes, quizzes, MCQs and sample papers.

Read More About Me →

Leave a Comment

error: Content is protected !!