LearningPython TutorialRegex, Date & Useful Standard Library
CHAPTER 20 · TEXT, TIME & STANDARD LIBRARY

Python Regex, Date & Useful Standard Library

Python ki standard library me text matching, date/time, maths, secure tokens, statistics aur efficient data handling ke liye ready-made modules milte hain. Is chapter me regular expressions ko carefully use karna aur practical standard-library tools ko real examples ke saath samjhenge.

English + Hinglish82 min readOnline practice included

What is the standard library?

Python standard library modules Python installation ke saath available hote hain, so common tasks ke liye har baar third-party package install karna required nahi hota. Import syntax same hoti hai: import module ya selective import.

Hinglish Explanation

Standard library ko built-in toolbox samjho. Har problem ke liye code zero se likhne ke bajay pehle check karo kya Python already reliable tool provide karta hai.

Regular expressions kya hote hain?

Regular expression, ya regex, text pattern describe karta hai. Python ka re module pattern search, validation, extraction aur replacement me useful hai.

regex-basic.pyPython
import re

text = "Order ID: BS-2048"
match = re.search(r"BS-\d+", text)

if match:
    print(match.group())

Raw string prefix r"..." regex patterns ke liye common hai because backslashes ko easier banata hai.

Try regex search →

Common regex symbols

  • . — usually any character except newline.
  • \d — digit character.
  • \w — word character.
  • \s — whitespace.
  • ^ — start of string/line context.
  • $ — end of string/line context.
  • * — zero or more.
  • + — one or more.
  • ? — zero or one; also affects quantifier behavior in some contexts.
  • {m,n} — bounded repetition.
  • [abc] — character class.
  • (...) — group.
  • | — alternative/or.

Use fullmatch() for complete validation

fullmatch.pyPython
import re

code = "PY-2026"
pattern = r"[A-Z]{2}-\d{4}"

if re.fullmatch(pattern, code):
    print("Valid code")
else:
    print("Invalid code")

re.search() kahin bhi matching part find kar sakta hai, while re.fullmatch() complete input ko pattern se match karne ke liye useful hai.

Capture groups

groups.pyPython
import re

text = "Aman scored 88"
match = re.search(r"(?P<name>[A-Za-z]+) scored (?P<score>\d+)", text)

if match:
    print(match.group("name"))
    print(int(match.group("score")))

Named groups complex patterns me numeric group positions se easier read hote hain.

findall(), finditer() and split()

extract.pyPython
import re

text = "Scores: 78, 92, 84"
print(re.findall(r"\d+", text))

for match in re.finditer(r"\d+", text):
    print(match.group(), match.start())

print(re.split(r"\s*,\s*", "HTML, CSS, Python"))

finditer() match objects deta hai, so positions/groups bhi inspect kar sakte ho.

Replace text with re.sub()

replace.pyPython
import re

phone = "98765-43210"
masked = re.sub(r"\d(?=\d{4})", "*", phone.replace("-", ""))
print(masked)

Regex replacement powerful hai, but sensitive data masking ke rules carefully define karo; regex alone security guarantee nahi.

Compile reusable patterns

compiled.pyPython
import re

student_id = re.compile(r"BS\d{5}")

for value in ["BS12345", "XX12345", "BS99887"]:
    print(value, bool(student_id.fullmatch(value)))

Compiled pattern readability aur repeated use improve kar sakta hai. Python internally some pattern compilation cache bhi karta hai, so use primarily for clarity/reuse.

Regex ko har jagah use mat karo

  • Simple prefix/suffix ke liye startswith()/endswith() easier ho sakte hain.
  • Exact separator parsing ke liye split() enough ho sakta hai.
  • Complex HTML/XML parsing regex se avoid karo; dedicated parsers use karo.
  • Untrusted or highly complex regex patterns catastrophic backtracking/performance issues create kar sakte hain.

datetime basics

datetime module dates, times, combined timestamps aur durations handle karta hai.

datetime-basic.pyPython
from datetime import date, datetime

today = date.today()
now = datetime.now()

print(today)
print(now)
Important: datetime.now() by default local, timezone-unaware datetime return karta hai. Networked applications me timezone handling explicitly plan karo.

Create date and datetime values

create-dates.pyPython
from datetime import date, datetime

course_start = date(2026, 9, 12)
class_time = datetime(2026, 9, 12, 18, 30)

print(course_start)
print(class_time)

Formatting with strftime()

format-date.pyPython
from datetime import datetime

now = datetime(2026, 9, 12, 18, 30)
print(now.strftime("%d-%m-%Y"))
print(now.strftime("%I:%M %p"))

Common directives: %Y year, %m month, %d day, %H 24-hour, %M minute, %S second.

Parse text with strptime()

parse-date.pyPython
from datetime import datetime

text = "12/09/2026"
parsed = datetime.strptime(text, "%d/%m/%Y")
print(parsed.date())

Input format mismatch hone par ValueError raise hota hai, so user input parsing me exception handling useful hai.

Try date parsing →

Date arithmetic with timedelta

timedelta.pyPython
from datetime import date, timedelta

today = date(2026, 9, 12)
next_week = today + timedelta(days=7)
print(next_week)
print((next_week - today).days)

timedelta fixed-duration arithmetic ke liye useful hai. Calendar-month arithmetic different problem hai because months equal length ke nahi hote.

Timezone-aware datetimes

timezone.pyPython
from datetime import datetime, timezone

now_utc = datetime.now(timezone.utc)
print(now_utc)
print(now_utc.isoformat())

UTC storage/interchange common practice hai. Regional timezone rules ke liye modern Python me zoneinfo module use kar sakte ho when timezone database is available.

ISO 8601 helpers

iso.pyPython
from datetime import datetime, timezone

value = datetime.now(timezone.utc)
encoded = value.isoformat()
restored = datetime.fromisoformat(encoded)

print(encoded)
print(restored)

Machine-readable timestamps ke liye ISO format often manual custom formatting se safer/clearer hota hai.

math module

math-tools.pyPython
import math

print(math.sqrt(81))
print(math.ceil(4.2))
print(math.floor(4.8))
print(math.pi)
print(math.gcd(48, 18))

math common mathematical functions/constants provide karta hai. Exact decimal money calculations ke liye floating-point limitations samajhna important hai; decimal module useful ho sakta hai.

Decimal for base-10 arithmetic

decimal.pyPython
from decimal import Decimal

price = Decimal("0.10")
tax = Decimal("0.20")
print(price + tax)

Decimal ko strings se construct karna common practice hai when decimal input exactly preserve karna ho.

random module

random-demo.pyPython
import random

skills = ["HTML", "CSS", "JavaScript", "Python"]
print(random.choice(skills))
print(random.randint(1, 10))

random.shuffle(skills)
print(skills)
Security: random passwords, OTPs, reset tokens or cryptographic secrets ke liye suitable nahi. Security-sensitive randomness ke liye secrets module use karo.

secrets for security-sensitive tokens

secure-token.pyPython
import secrets

print(secrets.token_hex(16))
print(secrets.token_urlsafe(16))

Token length/security requirement application context par depend karti hai. Generated secret ko logs ya public output me expose mat karo.

statistics module

statistics.pyPython
from statistics import mean, median

scores = [78, 92, 84, 67, 91]
print(mean(scores))
print(median(scores))

Basic descriptive statistics ke liye standard library enough ho sakti hai; large data-analysis workloads ke liye specialized libraries later useful hoti hain.

collections.Counter

counter.pyPython
from collections import Counter

words = "python css python html python css".split()
counts = Counter(words)
print(counts)
print(counts.most_common(2))

Frequency counting ke common pattern ko Counter concise bana deta hai.

defaultdict and deque

collections-tools.pyPython
from collections import defaultdict, deque

groups = defaultdict(list)
groups["python"].append("Aman")
groups["python"].append("Riya")
print(groups["python"])

queue = deque(["A", "B"])
queue.append("C")
print(queue.popleft())

deque efficient append/pop operations from both ends ke liye designed hai. Queue workflows me list ka pop(0) repeatedly use karne se better fit ho sakta hai.

itertools basics

itertools.pyPython
from itertools import chain, islice

combined = chain([1, 2], [3, 4])
print(list(combined))

first_three = islice(range(100), 3)
print(list(first_three))

itertools memory-friendly iterator building blocks deta hai. Infinite iterators ke saath always clear stopping strategy rakho.

Choose the simplest tool

  • Plain string method enough ho to regex mat force karo.
  • Date arithmetic ke liye strings manually manipulate mat karo; date/datetime objects use karo.
  • Security tokens ke liye random nahi, secrets.
  • Frequency counting ke liye manual dictionary valid hai, but Counter often clearer.
  • Queue ke liye deque suitable ho sakta hai.
  • Exact decimal arithmetic requirement ho to Decimal consider karo.

Common beginner mistakes

  • Regex me raw string use na karna and backslash escapes confuse karna.
  • search() ko complete validation samajhna instead of fullmatch().
  • Overly broad regex such as .* without clear constraints use karna.
  • Regex ko HTML parser ya every text task ka replacement samajhna.
  • Date ko display string form me store karke later arithmetic attempt karna.
  • strptime() format and input mismatch ignore karna.
  • Naive and timezone-aware datetimes ko mix karna.
  • Passwords/OTPs ke liye random use karna.
  • Float ko exact currency representation assume karna.
  • Standard-library class/function name ko local variable se shadow karna.

Beginner best practices

  • Regex patterns ko small, readable aur testable rakho.
  • Complex patterns me named groups consider karo.
  • Dates ko typed date/datetime values ke roop me process karo, strings only input/output boundaries par.
  • Timezone intent explicit rakho.
  • Machine exchange ke liye ISO-style date/time formats prefer karo.
  • Security-sensitive randomness ke liye secrets.
  • Standard library choose karne se pehle module docs and exact behavior verify karo.
  • Readable helper functions bana kar multiple utilities ko combine karo.

Chapter checklist

  • re.search(), fullmatch(), findall() and sub() ka role clear hai?
  • Common regex symbols and raw strings samajh aaye?
  • datetime.strptime()/strftime() use kar sakte ho?
  • timedelta se date arithmetic kar sakte ho?
  • Naive vs timezone-aware datetime ka basic difference clear hai?
  • math, Decimal, random and secrets kab use karne hain samajh aaya?
  • Counter, defaultdict, deque aur itertools ka beginner use clear hai?

Practice Task — Student Activity Utility

BrounStack Playground me standard-library based utility banao.

  1. Student ID format BS12345 ko regex se validate karo.
  2. Input text se all numeric scores extract karo.
  3. One named capture-group regex banao.
  4. dd/mm/yyyy date parse karo.
  5. Parsed date me 30 days add karo.
  6. Date ko readable format me print karo.
  7. UTC-aware current datetime generate karo.
  8. Scores ka mean and median calculate karo.
  9. Course names ki frequency Counter se nikalo.
  10. deque based small queue banao.
  11. Decimal se one exact amount calculation karo.
  12. random.choice() se non-security demo selection karo.
  13. secrets.token_hex() ka safe-token example add karo but token ko production logging me expose na karne ka comment likho.
  14. Code comments me explain karo kaha regex unnecessary hota.

Open practice starter →