Strings: Slicing और Methods
String क्या है?
String characters — letters, digits, spaces, symbols — का sequence है जो single, double या triple quotes में लिखा जाता है। Triple quotes से कई lines का text लिख सकते हैं।
name = 'Riya' city = "New Delhi" address = '''House 12, Sector 5''' print(name, city) print(address)
Indexing
हर character की एक position होती है जिसे index कहते हैं। Positive index बाईं ओर से 0 से शुरू होता है; negative index दाईं ओर से -1 से।
s = 'COMPUTER' print(s[0], s[3], s[-1], s[-3], len(s))
s = 'COMPUTER' print(s[10])
Slicing
s[start : stop : step] string का हिस्सा देता है — start से stop − 1 तक, step से कूदते हुए। Start न हो = शुरुआत; stop न हो = अंत; negative step = उल्टा चलो।
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
String operators
s = 'COMPUTER'
print('Hello' + ' ' + 'World') # concatenation
print('Ha' * 3) # repetition
print('PUT' in s, 'put' in s) # membership is case-sensitiveStrings को == < > से compare भी कर सकते हैं; comparison Unicode codes से character-दर-character होता है।
String traverse करना
Traversal यानी हर character पर एक-एक करके जाना, सीधे for loop से या indexes से।
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()Strings immutable हैं
s = 'COMPUTER' s[0] = 'K'
s = 'COMPUTER' s = 'K' + s[1:] # make a NEW string instead print(s)
String methods
Method एक function है जो किसी object का होता है और dot से call होता है: s.upper()। String methods नई string या value return करते हैं; original नहीं बदलती।
Case बदलना
x = 'python programming'
print(x.upper())
print(x.title())
print(x.capitalize())
print('MiXeD'.swapcase(), 'ABC'.lower())ढूँढना और बदलना
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'))जाँचना और trim करना
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()))Split और join
print('red,green,blue'.split(','))
print('one two three'.split()) # split on any spaces
print('-'.join(['2026', '10', '19']))
print('a-b-c'.partition('-'))| 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 गिनना
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)2. Palindrome string
w = input('Enter a word: ')
if w.lower() == w.lower()[::-1]:
print(w, 'is a palindrome')
else:
print(w, 'is not a palindrome')3. Word statistics
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))सारांश और practice
- Index बाईं ओर से 0 … n−1, दाईं ओर से −1 … −n।
s[a:b:c]slice करता है;s[::-1]उल्टा करता है।+जोड़ता,*दोहराता,inmembership check करता है।- Strings immutable हैं; methods नई strings return करते हैं।
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
