Building Strings
Exit

Building Strings

Construct strings with .join() and f-string formatting

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

.join()

.join() combines a list of strings into one string. The string you call it on becomes the separator.

words = ["Python", "is", "great"]
sentence = " ".join(words)   # "Python is great"

path = "/".join(["home", "user", "docs"])  # "home/user/docs"

Think of .join() as the opposite of .split(): .split() breaks a string into a list, .join() assembles a list into a string.

f-strings

f-strings embed Python expressions directly inside string literals. Prefix the string with f and wrap each expression in {}.

name = "Alice"
score = 95
print(f"Student: {name}, Score: {score}/100")
# Student: Alice, Score: 95/100

You can include any expression inside {}, including formatting:

price = 19.99
print(f"Total: ${price:.2f}")  # Total: $19.99

Instructions

Build strings using .join() and f-string formatting.

  1. Create words = ["Python", "is", "powerful"]. Assign " ".join(words) to sentence. Call print(sentence).
  2. Create name = "Alice" and score = 98. Assign f"Student: {name}, Score: {score}/100" to message. Call print(message).
  3. Assign "/".join(["home", "user", "documents"]) to path. Call print(path).