HomeCoursesPython
Chapter 10 of 14

স্ট্রিং মেথড

String slicing, methods, formatting, f-string & regular expression basics

String Basics ও Immutability

Python-এ string হলো characters-এর একটি ordered sequence। String immutable — একবার তৈরি হলে এর কোনো character সরাসরি পরিবর্তন করা যায় না। তবে নতুন string তৈরি করা যায়।

# String তৈরি
name = "Python"
greeting = 'আসসালামু আলাইকুম'
multiline = """এটি একটি
মাল্টিলাইন স্ট্রিং"""

# Indexing — প্রতিটি character-এর position আছে
print(name[0])    # P (প্রথম character)
print(name[-1])   # n (শেষ character)
print(len(name))  # 6 (মোট character সংখ্যা)

# Immutability — সরাসরি পরিবর্তন করা যায় না
# name[0] = "J"   # ❌ TypeError!
name = "Jython"   # ✅ নতুন string assign করা যায়
🔑 String Immutability কেন গুরুত্বপূর্ণ?
  • String immutable হওয়ায় এটি dictionary key এবং set-এর element হিসেবে ব্যবহার করা যায়
  • String method গুলো মূল string পরিবর্তন করে না — নতুন string রিটার্ন করে
  • যেকোনো method-এর ফলাফল একটি variable-এ সংরক্ষণ করতে হবে

String Slicing

Slicing দিয়ে string-এর যেকোনো অংশ বের করা যায়। Syntax: string[start:stop:step]

Sliceঅর্থউদাহরণ (s = "Python")ফলাফল
s[0:3]index 0 থেকে 2 পর্যন্ত"Python"[0:3]"Pyt"
s[2:]index 2 থেকে শেষ পর্যন্ত"Python"[2:]"thon"
s[:4]শুরু থেকে index 3 পর্যন্ত"Python"[:4]"Pyth"
s[::2]প্রতি ২য় character"Python"[::2]"Pto"
s[::-1]উল্টো করা (reverse)"Python"[::-1]"nohtyP"
text = "Bangladesh"

print(text[0:6])    # Bangla
print(text[6:])     # desh
print(text[-4:])    # desh
print(text[::2])    # Bnlds
print(text[::-1])   # hsedalgnaB

# Palindrome চেক — slicing দিয়ে
word = "madam"
if word == word[::-1]:
    print(f"'{word}' একটি palindrome!")  # 'madam' একটি palindrome!

Common String Methods

Python string-এ অনেক দরকারি built-in method আছে। এগুলো মূল string পরিবর্তন করে না, নতুন string রিটার্ন করে:

Methodকাজউদাহরণফলাফল
upper()সব বড় হাতের অক্ষরে"hello".upper()"HELLO"
lower()সব ছোট হাতের অক্ষরে"HELLO".lower()"hello"
strip()দু'পাশের whitespace সরায়" hi ".strip()"hi"
split(sep)String ভেঙে list তৈরি"a,b,c".split(",")['a','b','c']
join(iterable)List থেকে string তৈরি"-".join(['a','b'])"a-b"
replace(old,new)অংশ প্রতিস্থাপন"cat".replace("c","b")"bat"
find(sub)Substring-এর index (না থাকলে -1)"hello".find("ll")2
count(sub)Substring কতবার আছে"banana".count("a")3
# Method chaining — একাধিক method একসাথে
raw = "  Hello, World!  "
clean = raw.strip().lower().replace("!", "")
print(clean)  # hello, world

# split() ও join() — text processing-এ সবচেয়ে বেশি ব্যবহৃত
sentence = "আমি পাইথন শিখছি"
words = sentence.split()          # ['আমি', 'পাইথন', 'শিখছি']
joined = " | ".join(words)        # আমি | পাইথন | শিখছি

# CSV data parse করা
csv_line = "রহিম,22,CSE,3.75"
fields = csv_line.split(",")
print(fields)  # ['রহিম', '22', 'CSE', '3.75']

String Checking Methods

এই method গুলো True বা False রিটার্ন করে — input validation-এ বিশেষ কার্যকর:

MethodTrue রিটার্ন করে যখনউদাহরণ
startswith(prefix)নির্দিষ্ট prefix দিয়ে শুরু"Python".startswith("Py") → True
endswith(suffix)নির্দিষ্ট suffix দিয়ে শেষ"file.py".endswith(".py") → True
isdigit()সব character digit (0-9)"123".isdigit() → True
isalpha()সব character letter"abc".isalpha() → True
isalnum()সব character letter বা digit"abc123".isalnum() → True
isspace()সব character whitespace" ".isspace() → True
isupper()সব letter বড় হাতের"ABC".isupper() → True
islower()সব letter ছোট হাতের"abc".islower() → True
# Input validation উদাহরণ
phone = "01712345678"
if phone.isdigit() and len(phone) == 11:
    print("✅ সঠিক ফোন নম্বর")
else:
    print("❌ ভুল ফোন নম্বর")

# File extension চেক
filename = "report.pdf"
if filename.endswith((".pdf", ".doc", ".docx")):
    print("এটি একটি document file")

String Formatting

Python-এ string-এর ভেতরে variable-এর মান বসানোর বেশ কয়েকটি উপায় আছে:

# ১. f-string (Python 3.6+) — সবচেয়ে জনপ্রিয় ও সহজ
name = "রহিম"
age = 22
print(f"আমার নাম {name}, বয়স {age}")

# f-string-এ expression ব্যবহার
price = 150.5
print(f"মূল্য: {price:.2f} টাকা")     # মূল্য: 150.50 টাকা
print(f"বর্গ: {5**2}")                  # বর্গ: 25

# ২. .format() method
print("নাম: {}, বয়স: {}".format(name, age))
print("নাম: {n}, বয়স: {a}".format(n=name, a=age))

# ৩. % operator (পুরনো পদ্ধতি)
print("নাম: %s, বয়স: %d" % (name, age))

# Alignment ও padding
for item in ["আম", "জাম", "কাঁঠাল"]:
    print(f"{item:<10} ৫০ টাকা")   # Left align, 10 chars wide
💡 Formatting মনে রাখার কৌশল

f-string = fast ও friendly — সবচেয়ে দ্রুত ও পড়তে সহজ।
f"..." এর ভেতরে {} এর মধ্যে যেকোনো valid Python expression লেখা যায়।
:.2f = 2 decimal places, :<10 = left align 10 chars, :>10 = right align।

Regular Expression বেসিক

Regular expression (regex) হলো text pattern matching-এর শক্তিশালী টুল। Python-এ re module ব্যবহার করতে হয়:

import re

# re.search() — pattern খোঁজা (প্রথম match)
text = "আমার ফোন নম্বর 01712345678"
match = re.search(r'\d{11}', text)
if match:
    print(f"ফোন পাওয়া গেছে: {match.group()}")
    # ফোন পাওয়া গেছে: 01712345678

# re.findall() — সব match-এর list
emails = "info@abc.com এবং hr@xyz.org এ মেইল করুন"
found = re.findall(r'[\w.]+@[\w.]+', emails)
print(found)  # ['info@abc.com', 'hr@xyz.org']

# re.sub() — pattern replace
phone = "017-1234-5678"
clean = re.sub(r'-', '', phone)
print(clean)  # 01712345678
Patternঅর্থউদাহরণ
\dযেকোনো digit (0-9)\d{3} = ৩টি digit
\wLetter, digit, বা underscore\w+ = এক বা একাধিক
\sWhitespace (space, tab, newline)\s+ = এক বা একাধিক space
.যেকোনো character (newline ছাড়া)a.c = abc, adc, a1c
+এক বা তার বেশি বার\d+ = এক বা একাধিক digit
*শূন্য বা তার বেশি বারab*c = ac, abc, abbc
^String-এর শুরু^Hello
$String-এর শেষworld$
🔑 Regex ব্যবহারের টিপস
  • Regex pattern-এ raw string r'...' ব্যবহার করুন — backslash সমস্যা এড়াতে
  • সহজ কাজে str.find(), str.replace() ব্যবহার করুন — regex শুধু complex pattern-এ
  • re.compile() দিয়ে pattern compile করলে বারবার ব্যবহারে performance ভালো হয়
🧠 Quick Check
এই অধ্যায়ের উপর ৫টি প্রশ্নের উত্তর দিন
Q1. "Python"[::-1] এর output কী?
✅ সঠিক উত্তর: খ) nohtyP[::-1] slicing step -1 মানে string-কে উল্টো (reverse) করে দেয়। এটি palindrome চেকে বহুল ব্যবহৃত।
Q2. "hello world".split() কী রিটার্ন করবে?
✅ সঠিক উত্তর: খ) ['hello', 'world']split() argument ছাড়া call করলে whitespace দিয়ে ভাগ করে এবং একটি list রিটার্ন করে।
Q3. "123abc".isdigit() কী রিটার্ন করবে?
✅ সঠিক উত্তর: খ) Falseisdigit() তখনই True দেয় যখন সব character digit হয়। "123abc"-তে letter আছে, তাই False
Q4. f"মূল্য: {99.5:.2f} টাকা" এর output কী?
✅ সঠিক উত্তর: খ) মূল্য: 99.50 টাকা:.2f format specifier মানে দশমিকের পর ঠিক ২টি সংখ্যা দেখাবে। 99.5 হয়ে যায় 99.50।
Q5. Regex-এ \d+ কী match করে?
✅ সঠিক উত্তর: খ) এক বা একাধিক digit\d মানে একটি digit (0-9) এবং + মানে "এক বা তার বেশি বার"। তাই \d+ = এক বা একাধিক consecutive digit।
← Previous: ফাংশন Next: ফাইল হ্যান্ডলিং →