Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📦 Unit 2 – Strings, Lists, Tuples & Dictionaries  ·  Lesson 20

Strings: Slicing & Methods

What is a string?

A string is a sequence of characters — letters, digits, spaces, symbols — enclosed in single, double or triple quotes. Triple quotes allow text over many lines.

Python
name = 'Riya'
city = "New Delhi"
address = '''House 12,
Sector 5'''
print(name, city)
print(address)
Riya New Delhi House 12, Sector 5

Indexing

Each character has a position called an index. Positive indexes start at 0 from the left; negative indexes start at -1 from the right.

s →C0-8O1-7M2-6P3-5U4-4T5-3E6-2R7-1
s[3] and s[-5] are both "P"
Python
s = 'COMPUTER'
print(s[0], s[3], s[-1], s[-3], len(s))
C P R T 8
Python
s = 'COMPUTER'
print(s[10])
IndexError: string index out of range

Slicing

s[start : stop : step] gives a part of the string from start up to stop − 1, jumping by step. Missing start = beginning; missing stop = end; negative step = go backwards.

s[2:5] →C0O1M2P3U4T5E6R7
Start at index 2, stop before index 5 → "MPU"
Python
s = 'COMPUTER'
print(s[0:4], s[2:5], s[:3], s[5:])
print(s[::2], s[::-1], s[-3:], s[1:7:2])
print(repr(s[3:100]), repr(s[5:2]))     # slices never give an error
COMP MPU COM TER CMUE RETUPMOC TER OPT 'PUTER' ''

String operators

Python
s = 'COMPUTER'
print('Hello' + ' ' + 'World')     # concatenation
print('Ha' * 3)                    # repetition
print('PUT' in s, 'put' in s)      # membership is case-sensitive
Hello World HaHaHa True False

Strings can also be compared with == < >; comparison is done character by character using Unicode codes.

Traversing a string

Traversal means visiting every character one by one, using a for loop directly or with indexes.

Python
word = 'PYTHON'
for ch in word:                 # method 1: each character
    print(ch, end=' ')
print()
for i in range(len(word)):      # method 2: using index
    print(i, word[i], end=' | ')
print()
P Y T H O N 0 P | 1 Y | 2 T | 3 H | 4 O | 5 N |

Strings are immutable

Python
s = 'COMPUTER'
s[0] = 'K'
TypeError: 'str' object does not support item assignment
Python
s = 'COMPUTER'
s = 'K' + s[1:]           # make a NEW string instead
print(s)
KOMPUTER

String methods

A method is a function that belongs to an object and is called with a dot: s.upper(). String methods return a new string or value; the original is not changed.

Changing case

Python
x = 'python programming'
print(x.upper())
print(x.title())
print(x.capitalize())
print('MiXeD'.swapcase(), 'ABC'.lower())
PYTHON PROGRAMMING Python Programming Python programming mIxEd abc

Searching and replacing

Python
x = 'python programming'
print(x.count('m'), x.find('pro'), x.find('java'), x.index('g'))
print(x.replace('python', 'java'))
print(x.startswith('py'), x.endswith('ing'))
2 7 -1 10 java programming True True

Testing and trimming

Python
print('abc123'.isalnum(), 'abc'.isalpha(), '123'.isdigit())
print('abc'.islower(), 'ABC'.isupper(), '   '.isspace(), 'Hello World'.istitle())
t = '  Python is Fun  '
print(repr(t.strip()), repr(t.lstrip()), repr(t.rstrip()))
True True True True True True True 'Python is Fun' 'Python is Fun ' ' Python is Fun'

Splitting and joining

Python
print('red,green,blue'.split(','))
print('one two  three'.split())          # split on any spaces
print('-'.join(['2026', '10', '19']))
print('a-b-c'.partition('-'))
['red', 'green', 'blue'] ['one', 'two', 'three'] 2026-10-19 ('a', '-', 'b-c')
Method / functionReturns
len(s)Number of characters
s.upper(), s.lower(), s.title(), s.capitalize(), s.swapcase()New string with changed case
s.count(x)How many times x occurs
s.find(x) / s.index(x)First position of x (find gives -1 if absent)
s.replace(old, new)New string with replacements
s.startswith(x), s.endswith(x)True / False
s.isalpha(), isdigit(), isalnum(), islower(), isupper(), isspace(), istitle()True / False
s.strip(), lstrip(), rstrip()Spaces removed from both / left / right
s.split(sep), sep.join(list), s.partition(sep)List / string / 3-part tuple

Solved programs

1. Count vowels, consonants, digits and spaces

Python
text = input('Enter a sentence: ')
v = c = d = sp = 0
for ch in text:
    if ch.lower() in 'aeiou':
        v += 1
    elif ch.isalpha():
        c += 1
    elif ch.isdigit():
        d += 1
    elif ch == ' ':
        sp += 1
print('Vowels:', v, 'Consonants:', c, 'Digits:', d, 'Spaces:', sp)
Enter a sentence: Class 11 is Awesome Vowels: 6 Consonants: 8 Digits: 2 Spaces: 3

2. Palindrome string

Python
w = input('Enter a word: ')
if w.lower() == w.lower()[::-1]:
    print(w, 'is a palindrome')
else:
    print(w, 'is not a palindrome')
Enter a word: Malayalam Malayalam is a palindrome

3. Word statistics

Python
line = 'the quick brown fox jumps'
words = line.split()
print('Words:', len(words))
print('Longest:', max(words, key=len))
print('Each word capitalised:', ' '.join(w.capitalize() for w in words))
print('Initials:', ''.join(w[0].upper() for w in words))
Words: 5 Longest: quick Each word capitalised: The Quick Brown Fox Jumps Initials: TQBFJ

Summary & practice

  • Index 0 … n−1 from the left, −1 … −n from the right.
  • s[a:b:c] slices; s[::-1] reverses.
  • + joins, * repeats, in checks membership.
  • Strings are immutable; methods return new strings.
✅ Practice

For s = 'INFORMATICS' find: s[2:6], s[-4:], s[::3], s.count('I'), s.find('MAT'), s.lower().replace('i', '!').

Answers: FORM, TICS, IOAC, 2, 5, !nformat!cs

Frequently Asked Questions

What is the difference between find() and index()?
Both give the position of a substring. If it is not found, find() returns -1, but index() raises a ValueError.
How do I reverse a string in Python?
Use slicing with step -1: s[::-1]. For example "HELLO"[::-1] gives "OLLEH".
Why does s[0] = "K" give an error?
Strings are immutable, so their characters cannot be changed in place. Create a new string instead, for example s = "K" + s[1:].
← Class 11 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicLists: Operations & Methods Your progress: 20 / 29 (69%) · Lesson 21 / 29 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free