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.
name = 'Riya' city = "New Delhi" address = '''House 12, Sector 5''' print(name, city) print(address)
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 = 'COMPUTER' print(s[0], s[3], s[-1], s[-3], len(s))
s = 'COMPUTER' print(s[10])
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 = '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 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.
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 are immutable
s = 'COMPUTER' s[0] = 'K'
s = 'COMPUTER' s = 'K' + s[1:] # make a NEW string instead print(s)
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
x = 'python programming'
print(x.upper())
print(x.title())
print(x.capitalize())
print('MiXeD'.swapcase(), 'ABC'.lower())Searching and replacing
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'))Testing and trimming
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()))Splitting and joining
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 | Returns |
|---|---|
| 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
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))Summary & practice
- Index 0 … n−1 from the left, −1 … −n from the right.
s[a:b:c]slices;s[::-1]reverses.+joins,*repeats,inchecks membership.- Strings are immutable; methods return new strings.
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
