KTU S1

Strings as Sequences

By the end you should be able to: Index, slice and iterate over strings, use the common string methods, and explain the consequences of strings being immutable.

A string is a sequence of characters, so everything you learned about indexing and slicing lists applies unchanged.

s = "Kerala"

s[0]        # 'K'
s[-1]       # 'a'
s[1:4]      # 'era'      end excluded
s[:3]       # 'Ker'
s[::-1]     # 'alareK'   reversed
len(s)      # 6

Strings are immutable

This is the one real difference from lists.

s[0] = "M"          # TypeError
s = "M" + s[1:]     # make a NEW string instead

Every "modification" produces a new string. s.upper() does not change s; it returns a new one:

name = "anjali"
name.upper()            # 'ANJALI'
print(name)             # 'anjali'  — unchanged
name = name.upper()     # now name refers to the new string

Forgetting to reassign is one of the most common beginner bugs, and it fails silently — no error, just no effect.

Useful methods

s.upper()   s.lower()   s.title()       # case
s.strip()   s.lstrip()  s.rstrip()      # trim whitespace
s.replace("a", "o")                     # returns a new string
s.split()                               # on whitespace -> list
s.split(",")                            # on a separator
",".join(["a", "b", "c"])               # 'a,b,c'   list -> string
s.find("era")       # 1, or -1 if absent
s.index("era")      # 1, or ValueError if absent
s.count("a")        # 2
s.startswith("Ker") # True
"era" in s          # True

split() and join() are inverses and appear constantly:

"10 20 30".split()                  # ['10', '20', '30']
list(map(int, "10 20 30".split()))  # [10, 20, 30]

That second line is the standard way to read several numbers from one line of input, met in Module 1.

Checking content

"abc".isalpha()     # True
"123".isdigit()     # True
"a1".isalnum()      # True
"  ".isspace()      # True

isdigit() is the safe way to check input before converting:

raw = input("Enter your age: ")
if raw.isdigit():
    age = int(raw)
else:
    print("Please enter a whole number.")

Note "-5".isdigit() is False — the minus sign is not a digit. For negatives you need try/except or a manual check.

Iterating

for ch in "Kerala":
    print(ch)

vowels = sum(1 for ch in "Kerala".lower() if ch in "aeiou")   # 3

Building strings in a loop

result = ""
for ch in s:
    result += ch        # creates a NEW string every pass

Because strings are immutable this rebuilds the whole string each time. For short strings it is fine; for long ones, collect into a list and join once:

parts = []
for ch in s:
    parts.append(ch)
result = "".join(parts)

f-strings

Already met in Module 1, and the normal way to build output:

name, marks = "Anjali", 87.456
print(f"{name} scored {marks:.1f}")     # Anjali scored 87.5
print(f"{name:>10}|")                   # '    Anjali|'