Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
📦 Unit 2 – Strings, Lists, Tuples और Dictionaries  ·  Lesson 20

Strings: Slicing और Methods

String क्या है?

String characters — letters, digits, spaces, symbols — का sequence है जो single, double या triple quotes में लिखा जाता है। Triple quotes से कई lines का text लिख सकते हैं।

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

Indexing

हर character की एक position होती है जिसे index कहते हैं। Positive index बाईं ओर से 0 से शुरू होता है; negative index दाईं ओर से -1 से।

s →C0-8O1-7M2-6P3-5U4-4T5-3E6-2R7-1
s[3] और s[-5] दोनों "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] string का हिस्सा देता है — start से stop − 1 तक, step से कूदते हुए। Start न हो = शुरुआत; stop न हो = अंत; negative step = उल्टा चलो।

s[2:5] →C0O1M2P3U4T5E6R7
Index 2 से शुरू, 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 को == < > से compare भी कर सकते हैं; comparison Unicode codes से character-दर-character होता है।

String traverse करना

Traversal यानी हर character पर एक-एक करके जाना, सीधे for loop से या 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 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

Method एक function है जो किसी object का होता है और dot से call होता है: s.upper()। String methods नई string या value return करते हैं; original नहीं बदलती।

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

ढूँढना और बदलना

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

जाँचना और trim करना

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'

Split और join

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 / functionक्या return करता है
len(s)Characters की संख्या
s.upper(), s.lower(), s.title(), s.capitalize(), s.swapcase()बदले case वाली नई string
s.count(x)x कितनी बार आया
s.find(x) / s.index(x)x की पहली position (न मिले तो find -1)
s.replace(old, new)बदलाव वाली नई string
s.startswith(x), s.endswith(x)True / False
s.isalpha(), isdigit(), isalnum(), islower(), isupper(), isspace(), istitle()True / False
s.strip(), lstrip(), rstrip()दोनों / बाईं / दाईं ओर के spaces हटाकर
s.split(sep), sep.join(list), s.partition(sep)List / string / 3 हिस्सों का tuple

Solved programs

1. Vowels, consonants, digits और 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

सारांश और practice

  • Index बाईं ओर से 0 … n−1, दाईं ओर से −1 … −n।
  • s[a:b:c] slice करता है; s[::-1] उल्टा करता है।
  • + जोड़ता, * दोहराता, in membership check करता है।
  • Strings immutable हैं; methods नई strings return करते हैं।
✅ Practice

s = 'INFORMATICS' के लिए निकालें: 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

अक्सर पूछे जाने वाले प्रश्न (FAQ)

find() और index() में क्या फ़र्क है?
दोनों substring की position देते हैं। न मिले तो find() -1 return करता है, पर index() ValueError देता है।
Python में string उल्टी कैसे करें?
Step -1 के साथ slicing: s[::-1]। जैसे "HELLO"[::-1] से "OLLEH" मिलता है।
s[0] = "K" से error क्यों आती है?
Strings immutable हैं, इसलिए उनके characters उसी जगह नहीं बदल सकते। नई string बनाएँ, जैसे 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.

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

अगला topicLists: Operations और Methods आपकी प्रगति: 20 / 29 (69%) · Lesson 21 / 29 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें