Section 1 · Lesson 2

Strings and f-strings

Clean, slice and format text, and build readable report lines with f-strings.

25 min 3 practice tasks
Python Tutorial for Beginners 2: Strings - Working with Textual Data by Corey Schafer on YouTube

Most of the data you will touch arrives partly as text: campaign names, channels, emails, countries, even dates in a CSV. In Python, text values are strings (str), and cleaning them is a daily task for any analyst.

Creating strings

Wrap text in single or double quotes; both work the same way.

channel = "search"
advertiser = 'Summit Outdoor Co.'
note = "Don't pause this campaign"   # double quotes let you use an apostrophe inside

Indexing and slicing

A string is a sequence of characters, and each one has a position (an index) starting at 0. Square brackets pull out one character or a slice.

code = "CMP-2026-104"
code[0]      # 'C'      first character
code[-1]     # '4'      last character
code[4:8]    # '2026'   from index 4 up to (not including) 8
code[:3]     # 'CMP'    from the start
code[-3:]    # '104'    the last three
len(code)    # 12

The “up to but not including” rule trips everyone up at first: code[4:8] gives you characters 4, 5, 6 and 7.

Useful string methods

A method is a function attached to a value, called with a dot. These are the ones you will use constantly when cleaning data:

Method What it does Example Result
.strip() remove spaces at both ends " UK ".strip() 'UK'
.lower() / .upper() change case "Search".lower() 'search'
.title() capitalize each word "blue harbor".title() 'Blue Harbor'
.replace(a, b) swap text "2026/01/05".replace("/", "-") '2026-01-05'
.split(sep) break into a list of pieces "a@b.com".split("@") ['a', 'b.com']
.startswith(x) check the beginning "CMP-104".startswith("CMP") True

You can also test whether one string contains another with in: "Search" in "Northwind Traffic Search 3" is True.

Strings never change in place. A method returns a new string, so save the result:

name = "  summit search "
name.strip()          # returns 'summit search' but `name` is unchanged
name = name.strip()   # now `name` holds the cleaned value

Methods can be chained, read left to right: name.strip().title().

.split() returns a list, a collection you will meet properly in the next section. For now, [0] gets the first piece and [1] the second.

f-strings: putting values into text

Joining text with + gets clumsy fast, and it fails if you mix in a number ("Clicks: " + 742 raises a TypeError). An f-string is easier: put an f before the opening quote and write any variable inside {}.

campaign = "Summit Search"
clicks = 742
print(f"{campaign} got {clicks} clicks")   # Summit Search got 742 clicks

Add a format spec after a colon to control how numbers look:

Spec Meaning f"{x:spec}" with x = 18234.567
.2f 2 decimals 18234.57
,.2f thousands separator + 2 decimals 18,234.57
,.0f thousands separator, no decimals 18,235
.1% fraction as a percentage f"{0.0187:.1%}" gives 1.9%

Tip: Format specs change how a number is displayed, not the number itself. Keep raw numbers for calculations and format them only at the end, when you print or report.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Clean up a campaign name

A campaign name was typed into a spreadsheet with stray spaces and random capitals: raw_name = " summit CONVERSIONS video 1 ".

1. Create clean_name: remove the spaces at both ends and put it in title case, so it reads "Summit Conversions Video 1". 2. Create name_length: the number of characters in clean_name (use len()).

Need a hint?
  1. .strip() removes spaces (and tabs/newlines) from both ends of a string.
  2. .title() capitalizes the first letter of every word and lowercases the rest.
  3. Methods can be chained: raw_name.strip().title().
Python 3
raw_name = "   summit CONVERSIONS video 1  "

clean_name = raw_name
name_length = 0

print(repr(clean_name), name_length)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
2

Split an email address

A customer signed up with email = "Nora.Khan3@Example.com". Email addresses are not case-sensitive, so the CRM stores them in lowercase.

Create two variables, both lowercase:

  • username: the part before the @ (should be "nora.khan3")
  • domain: the part after the @ (should be "example.com")
Need a hint?
  1. "a@b".split("@") returns ["a", "b"]; [0] is the first piece and [1] the second.
  2. Call .lower() on the email before (or after) splitting.
Python 3
email = "Nora.Khan3@Example.com"

username = ""
domain = ""

print(username, domain)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
3

A report line with an f-string

Build a one-line campaign summary for a weekly email. You are given:

campaign = "Northwind Traffic Search 3"
spend = 18234.5
ctr = 0.01873        # a fraction: 1.873%

Create a variable report equal to exactly:

Northwind Traffic Search 3: $18,234.50 spent, CTR 1.87%

Use an f-string that inserts the three variables (don't retype the numbers): :,.2f adds thousands separators and 2 decimals, and :.2% turns a fraction into a percentage.

Need a hint?
  1. Start with f"{campaign}: ..."; anything inside {} is replaced by its value.
  2. The dollar sign is plain text, so it goes right before the braces: ${spend:,.2f}.
  3. {ctr:.2%} multiplies by 100, rounds to 2 decimals and adds the % sign.
Python 3
campaign = "Northwind Traffic Search 3"
spend = 18234.5
ctr = 0.01873

report = "TODO"
print(report)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country