Tutorial

Python Fundamentals Master: Strings, Regex, and Data Structures in 30 Questions

Complete Python fundamentals — slicing, f-strings, regex, lists, dicts, and file handling — 30 questions with explained solutions.

Anuj SainiAug 23, 20264 min read

Thirty questions that turn scattered Python syntax into a coherent base — strings, regex, lists, dicts, comprehensions, and file handling — with solutions you rerun until they are one-liners.

What ladder do the 30 questions climb?

Strings & regex (Q1-10) -> Lists (Q11-18) -> Dicts/sets (Q19-24) -> Comprehensions & functions (Q25-30), each mapped to focused video references (Strings & Methods, Regex, Lists Basics). If you prefer a smaller set first, do String assignments 5Q then return — the vocab repeats by design. Tabular continuation is Pandas fundamentals.

Ingredients: 30 prompts with starter variables (course = "Python Programming", text = " hello world " etc.) so you only write the targeted verb.

How do you master strings and regex?

python
# Q1-Q4: Slicing, negative indexing, methods, f-strings
course = "Python Programming"
print(course[0:6])        # Python — stop exclusive
print(course[-1])         # g — last char
text = "   hello world   "
print(text.strip().upper())  # HELLO WORLD
 
name="Alice"; age=30
print(f"My name is {name} and I am {age} years old.")
 
# Q5-Q6: Regex — digits & email
import re
print(re.findall(r'\d+', "Order 42 has 7 items"))  # ['42','7']
email_pat = r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}'
print(bool(re.match(email_pat, "student.name@university.edu")))  # True
 
# Q7: Split & join
print("a,b,c".split(","))
print("-".join(["Top","folio"]))

Rendered output showcases the four string invariants: slicing never IndexErrors out of range (it truncates), strip() removes only ends, f-strings beat +, and findall returns a list that may be empty — always check length before indexing.

How do you use lists, dicts, and comprehensions?

python
# Lists — append/extend/slice
fruits = ["apple","banana","cherry"]
fruits[1] = "orange"
fruits.append("grape")
print(fruits[1:3])  # ['orange','cherry']
 
# Dicts — get, update, iteration
capitals = {"USA":"Washington DC", "India":"New Delhi"}
capitals["France"] = "Paris"
print(capitals.get("Japan","Unknown"))
for k,v in capitals.items():
    print(k, "->", v)
 
# Comprehension: squares of evens
print([x*x for x in range(6) if x%2==0])  # [0, 4, 16]
print({k: len(v) for k,v in capitals.items()})  # city name lengths
python
# File handling — minimal safe pattern
path = "/tmp/demo.txt"
with open(path, "w") as f:
    f.write("Topfolio\n")
with open(path) as f:
    print(f.read())
Feature / Criteria

Gotcha: findall Returns a List — Not a String

Writing re.findall(...)[0] without checking emptiness crashes on clean strings. Guard with m = re.findall(...); token = m[0] if m else "". The notebook catches a traceback on a review with no digits.

Where do you go after fundamentals?

Use comprehensions to build DataFrame inputs and regex to clean Review text per VoC text mining. Then start tabular work in Pandas fundamentals — the syntax you just drilled reappears as .str and apply.


Download the Notebook and Practise

This article is a walkthrough of a runnable Jupyter notebook. Download the original .ipynb and run it locally or on Colab — every code block above appears in order.

Download the Python Fundamentals Master Notebook

Get the complete .ipynb with outputs — runs on any Python 3.10+ environment with pandas, numpy, and the libraries listed in setup.

Download .ipynb

Continue your track: Data Analyst Roadmap · Python and Pandas Guide · SQL NULL Handbook · SQL JOIN Fan-Out · Topfolio Practice · Data Analyst vs Engineer

Dataset generators where applicable are in courses/workbooks/generators/ — see citations atop for the exact *.py source for this notebook.


Frequently Asked Questions

What is the difference between slicing and indexing?

Indexing returns one element (s[0]), slicing returns a subsequence (s[0:6]). Slicing never raises IndexError out of range — it truncates safely.

How do f-strings work?

Prefix with f and embed {expr}: f"{name} is {age}" evaluates expressions inline. Faster and clearer than + concatenation.

When do you use regex vs string methods?

String methods (.split, .replace) for fixed patterns; re for variable patterns like emails or digits (re.findall(r'\d+', text)).

What is the gotcha with mutable defaults?

def f(lst=[]): reuses the same list across calls. Use def f(lst=None): lst = [] if lst is None.

Frequently Asked Questions

What is the difference between slicing and indexing?

Indexing returns one element (s[0]), slicing returns a subsequence (s[0:6]). Slicing never raises IndexError out of range — it truncates safely.

How do f-strings work?

Prefix with f and embed {expr}: f'{name} is {age}' evaluates expressions inline. Faster and clearer than + concatenation.

When do you use regex vs string methods?

String methods (.split, .replace) for fixed patterns; re for variable patterns like emails or digits (re.findall(r'\d+', text)).

What is the gotcha with mutable defaults?

def f(lst=[]): reuses the same list across calls. Use def f(lst=None): lst = [] if lst is None.

Anuj Saini

Written by

Anuj SainiFounder & Lead Instructor

Founder at Topfolio with 6+ years in data & analytics across JPMC, Ultrahuman, and high-growth startups. Sat on hiring panels, reviewed 500+ resumes, and writes practical SQL & data guides.