Strings — Deep Dive

স্ট্রিং — immutable sequence-এর গভীর বিশ্লেষণ

Read: ~35 min Intermediate 5 practice problems Live code runner

1. What a String Really Is

In Python, a string (str) is an immutable sequence of Unicode code points. "Immutable" means once a string exists, you cannot change it — every operation that looks like a change actually produces a new string.

Python-এ str হলো একটি immutable Unicode sequence — একবার তৈরি হলে আর পরিবর্তন করা যায় না। "পরিবর্তন"-এর মতো দেখালেও প্রতিটি operation আসলে একটি নতুন string তৈরি করে। এই immutability-ই Python-কে নিরাপদ ও হ্যাশযোগ্য করে তোলে।

2. Creating Strings

strings.py
single = 'hello'
double = "world"
multi  = """This is
a multi-line
string."""
bangla = "বাংলাদেশ"
raw    = r"C:\Users\abcl"        # backslashes literal
fstr   = f"Length = {len(bangla)}"   # f-string

print(single, double)
print(multi)
print(bangla, len(bangla))
print(raw)
print(fstr)
Single/double quote একরকম কাজ করে। """...""" multi-line-এর জন্য। r"..." raw string — backslash-কে literal রাখে (regex ও Windows path-এ কাজে লাগে)। f"..." expression-কে সরাসরি embed করে।

3. Indexing & Slicing — s[a:b:c]

Strings are sequences, so you can index them starting from 0, and use slices to extract sub-strings.

P y t h o n 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1 Positive indices go 0 → n-1, negative indices go from the right. Figure 13.1 — Indexing "Python" from both directions.
slicing.py
s = "Python Programming"

print(s[0])        # P
print(s[-1])       # g  (last char)
print(s[0:6])      # Python
print(s[7:])       # Programming
print(s[:6])       # Python
print(s[::2])      # Pto rgamn  (every 2nd char)
print(s[::-1])     # reversed

# length
print(len(s))      # 18

4. The 30+ String Methods You Actually Use

Python's str has over 40 methods. Here are the essentials every programmer uses daily.

MethodPurposeExample
.lower() .upper() .title()Change case"AbC".lower() → "abc"
.strip() .lstrip() .rstrip()Trim whitespace" hi ".strip() → "hi"
.split(sep)Split into list"a,b,c".split(",") → ["a","b","c"]
.join(iterable)Join with separator",".join(["a","b"]) → "a,b"
.replace(old, new)Replace all occurrences"aXb".replace("X","Y") → "aYb"
.startswith(p) / .endswith(s)Prefix / suffix check"file.py".endswith(".py") → True
.find(sub) / .index(sub)Search. find → -1, index → error"banana".find("na") → 2
.count(sub)Count occurrences"banana".count("a") → 3
.isdigit() .isalpha() .isalnum()Character-class checks"123".isdigit() → True
.zfill(n) .ljust(n) .rjust(n)Pad"7".zfill(3) → "007"
.format() / f"..."Format stringsf"{x:.2f}"
methods.py
raw = "   Hello, Python World!   "

print(raw.strip())
print(raw.strip().lower())
print(raw.strip().replace("Python", "Bangla"))
print(raw.strip().split(", "))

# build a sentence
parts = ["ABCL", "TECH", "Courses"]
print(" · ".join(parts))

# format
price = 1299.5
print(f"Price: {price:,.2f} BDT")

5. Immutability — And Why It Matters

s[0] = "X" raises TypeError. String methods never modify in place — they return new strings. This makes strings hashable (so they can be dict keys or set elements) and safe to share.

immutable.py
s = "cat"
print(id(s), s)

s = s.upper()            # creates a NEW string
print(id(s), s)    # different id — different object

# assignment rebinds the name; old "cat" is garbage-collected

# hashable, so can be a dict key
d = {"cat": 1, "dog": 2}
print(d["cat"])

6. Encoding — str vs bytes, UTF-8 and Bangla

A Python str is Unicode (code points). To store or transmit, you need bytes in some encoding — UTF-8 is the de-facto standard. Bangla characters use 3 bytes each in UTF-8.

encoding.py
text = "বাংলা"
print(len(text))                       # 5  (characters)

encoded = text.encode("utf-8")
print(encoded)                         # b'\xe0\xa6\xac...'
print(len(encoded))                    # 15 (bytes — 3 per char)

decoded = encoded.decode("utf-8")
print(decoded == text)                  # True
len(text) অক্ষর গোনে, bytes গোনে না। ফাইল read/write-এর সময় সবসময় encoding="utf-8" দিন — Bangla, Emoji, চাইনিজ — সব নিরাপদে হ্যান্ডেল হবে।

7. Vocabulary

TermMeaningবাংলায়
ImmutableCannot be changed after creation.তৈরির পর পরিবর্তন করা যায় না।
SliceSub-sequence via [a:b:c].[a:b:c] দিয়ে নেওয়া অংশ।
Code pointA Unicode character value.একটি Unicode অক্ষর।
EncodingCode points → bytes.Code point-কে bytes-এ রূপান্তর।
UTF-8Variable-length encoding, dominant on the web.পরিবর্তনশীল দৈর্ঘ্যের encoding।
Raw stringr"..." — backslashes are literal.r"..." — backslash literal।

8. Practice Problems

  1. Reverse a string without using [::-1].
    [::-1] ছাড়া একটি string উল্টান।
    ✨ Show Answer
    ans1.py
    def reverse(s):
        out = ""
        for ch in s:
            out = ch + out
        return out
    
    print(reverse("Python"))
  2. Check whether a string is a palindrome (ignoring case).
    একটি string palindrome কিনা check করুন (case ignore করে)।
    ✨ Show Answer
    ans2.py
    def is_palindrome(s):
        s = s.lower()
        return s == s[::-1]
    
    print(is_palindrome("Level"))
    print(is_palindrome("Python"))
  3. Count the number of vowels in a sentence.
    একটি বাক্যে vowel-এর সংখ্যা গণনা করুন।
    ✨ Show Answer
    ans3.py
    sentence = "Learning Python is wonderful"
    vowels = "aeiouAEIOU"
    count = sum(1 for c in sentence if c in vowels)
    print(f"Vowels: {count}")
  4. Why can a string be a dict key but a list cannot?
    কেন string dict-এর key হতে পারে কিন্তু list পারে না?
    ✨ Show Answer

    Dict keys must be hashable. Hashability requires the object's hash value to never change during its lifetime — which in turn requires immutability. Strings are immutable, so their hash is stable. Lists are mutable, so their hash could change after insertion and break the dict.

    Dict-এর key অবশ্যই hashable হতে হবে। Hash মান object-এর পুরো জীবনকালে একই থাকতে হবে, যা immutability দাবি করে। String immutable, তাই hash স্থির। List mutable — hash বদলাতে পারে, তাই key হিসেবে ব্যবহার নিষিদ্ধ।

  5. Given "2025-04-17", split into year/month/day and print "17 April 2025".
    "2025-04-17" থেকে year/month/day বের করে "17 April 2025" প্রিন্ট করুন।
    ✨ Show Answer
    ans5.py
    months = ["January","February","March","April","May","June",
              "July","August","September","October","November","December"]
    
    date = "2025-04-17"
    y, m, d = date.split("-")
    print(f"{int(d)} {months[int(m)-1]} {y}")

Summary — Module 13

A Python string is an immutable sequence of Unicode characters. Index with s[i], slice with s[a:b:c], and transform with the huge family of built-in methods. Strings never change in place — methods return new strings. Encode to bytes (UTF-8 preferred) when talking to files, sockets, or APIs.

Python-এর string — Unicode character-এর immutable sequence। s[i] দিয়ে index, s[a:b:c] দিয়ে slice। Method-গুলো নতুন string return করে, original অপরিবর্তিত থাকে। File/network-এ লেখার সময় UTF-8-এ encode করুন।

Next Module → Lists — Python-এর সবচেয়ে ব্যবহৃত mutable sequence।