Getting Started with Programming

Working with Strings


Learning Objectives

  • You understand a string as a sequence of characters.
  • You can use f-strings to insert values into a piece of text and explain the syntax.
  • You can use + to concatenate two strings and recognize when concatenation is the right tool.
  • You can apply common string methods such as .upper(), .lower(), and .strip().
  • You can access a single character of a string by its index.

Most of the values your programs handle in this part are strings — text. The user’s name is a string. The user’s choice of subject is a string. The greeting your program prints back is a string. This chapter looks at the most common things you do with text in Python.

Strings Hold Text

A string is a sequence of characters. In Python, strings are written between quotation marks. Both single and double quotes work, as long as the same kind is used at both ends.

message = "hello"
other_message = 'hello'

Strings can be empty, can contain spaces, can contain digits (still as text, not as numbers), and can be as long as you like.

empty = ""
greeting = "Hi there!"
order_number = "00417"

The order_number value above is text, not the number 417. Strings preserve the leading zeros and any other characters exactly.

String values

0 / 5 points

Which of these is a Python string?

A Closer Look at f-strings

You have been using f-strings since Print and Input. They are the default tool for building a piece of text out of fixed parts and variable values.

The rules are:

  • The opening quote is preceded by an f.
  • Anywhere inside the string, {expression} is replaced by the value of that expression when the line runs.
  • Everything else in the string is left exactly as written.
name = "Ada"
greeting = f"Hello, {name}!"
print(greeting)

This program prints Hello, Ada!. The placeholder {name} was replaced with the value Ada, and the surrounding text was kept as is.

What goes inside the { } does not have to be a single variable name. Any Python expression works, and the expression is evaluated first:

minutes = 90
print(f"That is {minutes / 60} hours.")

This prints That is 1.5 hours. Inside the braces, minutes / 60 was evaluated to 1.5, and that value was inserted into the string.

f-strings can have several placeholders. The substitution happens in order:

subject = "Math"
minutes = 45
day = "Tuesday"
print(f"Logged {minutes} minutes of {subject} on {day}.")

This prints Logged 45 minutes of Math on Tuesday.

The f-string reads almost like the sentence it is building, with blanks where the values go. That is the main reason this is the default style in the course: it stays readable as the number of values grows.

A small detail worth knowing: numbers are converted to text automatically inside an f-string. The line above worked because Python turned 45 into "45" as part of building the message. The same applies to most other values.

A Bond-style greeting

0 / 10 points

Ask the user for their first name and last name. Store both answers in variables.

Print one Bond-style greeting using an f-string in this exact format:

My name is {last_name}, {first_name} {last_name}.

Example input:

James
Bond

Required output text:

My name is Bond, James Bond.

The exact input prompts may differ. The required output line above must appear exactly as written for the input shown.

Joining Strings with +

There is also a lower-level way to combine strings: the + operator joins two strings into a longer one. This is called concatenation.

first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name)

This program prints Ada Lovelace. Three pieces are joined: first_name, the literal string " " (a single space), and last_name. Notice that the space between the names is its own little string. Python does not add spaces for you. If you want a space, you have to write it.

+ is most useful when you have two existing string values that you want to join together end-to-end, with no fixed text around them. The full-name example above is a good fit: both halves come from variables, and the result is just one joined to the other.

For “fill in the blanks” patterns — a fixed sentence with values inserted — f-strings are clearer. Compare:

print("Logged " + minutes + " minutes of " + subject + " on " + day + ".")

with:

print(f"Logged {minutes} minutes of {subject} on {day}.")

The two lines produce the same output (when minutes, subject, and day are all strings — see below). The f-string version reads more like the sentence; the + version reads as a chain of joins with the fixed text broken up between operators. Use + when you really are joining string pieces. Use f-strings when you are templating values into a sentence.

An important catch: + only works on two strings. It does not work between a string and a number. "Logged " + 45 raises a TypeError. f-strings convert numbers automatically; + does not. You will see this difference again in Numbers and Arithmetic.

Try string concatenation

0 / 10 points

Ask the user for a first name and a last name. Store both answers in variables.

Try using string concatenation to print the full name with exactly one space between the first and last name.

Example input:

Ada
Lovelace

Required output text:

Ada Lovelace

Common String Methods

Strings come with a number of built-in operations, called methods. A method is called using the dot notation: you write the string (or a variable holding one), a dot, and the method name with parentheses.

A few methods you will use often:

MethodWhat it doesExample
.upper()returns an upper-case version"Ada".upper() → "ADA"
.lower()returns a lower-case version"Ada".lower() → "ada"
.strip()removes whitespace from the ends" hi ".strip() → "hi"
.replace(a, b)replaces every a with b"abc".replace("a", "x") → "xbc"

For example:

name = input("What is your name? ")
clean_name = name.strip()
print(f"Hello, {clean_name}!")

This program is a small piece of defensive code. Users sometimes type an extra space at the beginning or the end of their answer without noticing. .strip() removes those spaces so the greeting looks right.

Each of these methods returns a new string. It does not change the original. That is why the example assigns the result to clean_name, rather than just calling name.strip() and expecting name to be different afterward.

Clean a subject name

0 / 10 points

Ask the user what subject they studied.

Use .strip() and .lower() to clean the answer, then print the cleaned subject name.

Example input:

Mathematics

Required output text:

mathematics

A String Has Positions

Because a string is an ordered sequence of characters, its characters can be accessed by position.

word = "python"
print(word[0])
print(word[1])

This prints two lines: p and y. The number inside the square brackets is called an index. In Python, indexing starts from 0, not from 1.

Index012345
Characterpython

If you try to access an index that does not exist, Python reports an error. For the string "python", the valid indexes are 0 through 5. Asking for word[10] would not silently return something — it would raise an IndexError.

Negative indexes are also allowed and count from the end: word[-1] is the last character. This is sometimes convenient. For now, it is enough to know that it exists.

Indexing starts at zero

0 / 5 points

What does this program print?

word = "python"
print(word[1])

How Long Is a String?

The built-in function len(...) returns the number of characters in a string.

word = "python"
print(len(word))

This prints 6. len(...) is one of the most useful tools you have when working with text: it tells you how much you have. You will see it again the next part when lists arrive, because the same function works for them too.

Length and first character

0 / 5 points

Build a program that prints the length of word and then its first character.

A Small Example with Several Operations

To pull these ideas together, here is a short program that takes a raw user answer, cleans it up, and shows a small summary:

raw_subject = input("What subject did you study? ")
subject = raw_subject.strip().lower()
minutes_text = input("For how many minutes? ")
print(f"Logged {minutes_text} minutes of {subject}.")
print(f"That subject name is {len(subject)} characters long.")

The first interesting line is subject = raw_subject.strip().lower(). This chains two string methods together. First .strip() removes whitespace; then .lower() is called on the result. By the time the value reaches subject, it is both cleaned up and in lowercase.

The rest of the program uses what you have already seen: f-strings, print, and len.

Check Your Understanding

  1. What does the f before the opening quote of a string do? What is inside { } in an f-string?
  2. Rewrite the following line as an f-string: print("You read " + book + " in " + days + " days.")
  3. When does + produce a TypeError, and what does an f-string do differently in the same situation?
  4. What does " Hello ".strip().upper() evaluate to?
  5. Why is word[10] an error if word is "python"?