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/100You 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.
- Create
words = ["Python", "is", "powerful"]. Assign" ".join(words)tosentence. Callprint(sentence). - Create
name = "Alice"andscore = 98. Assignf"Student: {name}, Score: {score}/100"tomessage. Callprint(message). - Assign
"/".join(["home", "user", "documents"])topath. Callprint(path).
# Step 1: Create words list, join with spaces into sentence, and print # Step 2: Create name and score, build message with f-string, and print # Step 3: Join path segments with "/" and print
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding