Lesson 3 of 4
Work with text: create and join strings, pick out characters and slices, use string methods, and format numbers neatly with f-strings.
About 30 minutes
upper(), strip(), replace() and split()A string is a sequence of characters: letters, digits, spaces and symbols. Strings are written inside single or double quotes. Both work the same way, which is useful when the text itself contains a quote.
element = "copper"structure = 'face-centred cubic'note = "Copper's lattice constant is 3.615 Å"print(element)print(structure)print(note)Text that spans several lines goes inside triple quotes (""" or '''). The line breaks are kept.
header = """Sample: Cu-01Operator: A. Researcher"""print(header)The + operator joins (or concatenates) strings, and * repeats a string. len() counts how many characters a string contains, including spaces.
element = "copper"symbol = "Cu"label = element + " (" + symbol + ")"print(label)print("-" * 12)print(len(element))Strings and numbers don't mix with +
"Mass: " + 12 raises a TypeError, because Python won't guess whether you want text or arithmetic. Convert the number first with str(12), use commas in print(), or use an f-string (shown later in this lesson).Each character in a string has a position number called an index. Python counts from 0, so the first character is at index 0, the second at index 1, and so on. Put the index in square brackets after the string to get that character. Negative indexes count from the end: -1 is the last character.
| Character | C | o | p | p | e | r |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
element = "Copper"print(element[0])print(element[3])print(element[-1])A slice takes a section of a string with [start:stop]. It includes the character at start but stops before stop. Leave out start to begin at the beginning, or leave out stop to go to the end.
sample_id = "CU-2024-017"print(sample_id[0:2]) # characters 0 and 1print(sample_id[3:7]) # characters 3 to 6print(sample_id[-3:]) # the last three charactersSlicing is very useful for codes and identifiers with a fixed layout, such as sample IDs, dates or file names.
A method is a function that belongs to a value. You call it with a dot after the value: element.upper(). Strings have many useful methods. Strings can't be changed once created (they are immutable), so these methods return a new string rather than changing the original.
| Method | What it does | Example | Result |
|---|---|---|---|
upper() | All upper case | "cu".upper() | "CU" |
lower() | All lower case | "FCC".lower() | "fcc" |
title() | Capitalise each word | "silicon carbide".title() | "Silicon Carbide" |
strip() | Remove spaces at both ends | " Fe ".strip() | "Fe" |
replace(a, b) | Replace every a with b | "Fe-Ni".replace("-", "/") | "Fe/Ni" |
count(x) | Count occurrences of x | "GATTACA".count("A") | 3 |
startswith(x) | Does it start with x? | "CU-01".startswith("CU") | True |
split(x) | Break into a list of parts at each x | "Fe,Cr,Ni".split(",") | ['Fe', 'Cr', 'Ni'] |
split() returns a list, which you will study in the Data Structures module. For now, think of it as an ordered collection of the pieces.
An alloy is recorded as a hyphen-separated list of elements. String methods tidy it up and break it into parts.
alloy = " fe-cr-ni "alloy = alloy.strip().upper()print(alloy)print(alloy.split("-"))print(alloy.count("-") + 1, "elements")The in operator checks whether one string appears inside another and gives True or False.
formula = "Fe2O3"print("O" in formula)print("Cu" in formula)Building messages with + and str() quickly becomes messy. An f-string is a string with an f before the opening quote. Inside it, anything in curly braces {} is replaced by its value. You can put variables or whole expressions inside the braces.
element = "copper"density = 8.96print(f"The density of {element} is {density} g/cm³")print(f"Twice the density is {density * 2} g/cm³")After the value you can add a colon and a format specifier that controls how it is displayed. This is the standard way to show a sensible number of decimal places.
| Specifier | Meaning | Example | Result |
|---|---|---|---|
:.2f | 2 decimal places | f"{3.14159:.2f}" | 3.14 |
:.0f | No decimal places (rounded) | f"{298.6:.0f}" | 299 |
:.3e | Scientific notation, 3 decimals | f"{6.02214e23:.3e}" | 6.022e+23 |
:, | Thousands separators | f"{3100000000:,}" | 3,100,000,000 |
:.1% | Percentage, 1 decimal | f"{0.4:.1%}" | 40.0% |
volume = 3.615 ** 3print(f"Unit cell volume: {volume:.2f} ų")print(f"Avogadro's number: {6.02214076e23:.3e}")A backslash \ inside a string starts an escape sequence: a way to write characters you can't type directly. The most common are \n for a new line and \t for a tab.
print("Element\tDensity")print("Cu\t8.96\nAl\t2.70")Choose an answer and press Check answer. You can retry as often as you like.