Strings and text output
Working with strings and text output
Text is everywhere in Python programs. File paths, filenames, HTML, messages, and generated content are all represented as text. This lesson exists to orient us to how Python handles text so we can start producing useful output in real programs, including simple generated web pages.
Creating string values
In Python, text values are called strings. A string is created by surrounding text with quotes.
We can use single quotes or double quotes. Python treats them the same, as long as they match.
title = "Mars"
subtitle = 'The Red Planet'
At this point, title and subtitle are variables that refer to string values.
Combining strings with other values
Programs often need to combine text with values that are not strings, such as numbers. Python does not automatically merge these for us.
Before combining, non-string values must be converted into strings.
planet = "Mars"
moons = 2
description = planet + " has " + str(moons) + " moons"
Here, str() converts the number into a string so it can be combined with other text.
Basic string operations
Strings support a small set of simple operations that show up frequently.
Concatenation joins strings together using +.
heading = "<h1>" + "Mars" + "</h1>"
Repetition repeats a string using *.
divider = "-" * 40
These operations are basic, but they are often enough for generating structured text like HTML.
Formatting text output
As programs grow, simple concatenation becomes harder to read. Python provides lightweight formatting tools that make intent clearer.
One common approach is f-strings, which allow values to be embedded directly inside text.
planet = "Mars"
radius_km = 3389
line = f"<p>{planet} has a radius of {radius_km} km.</p>"
This style keeps the structure of the text visible while clearly showing where values are inserted.
Displaying strings and values together as output
The built-in print() function sends text to the program’s output. It automatically converts values to strings when needed.
planet = "Mars"
moons = 2
print(planet, "has", moons, "moons")
When generating content, this output might later be redirected to a file instead of the screen, but the mechanics are the same.
Conclusion
We now know what strings are, how to create them, and how to combine them with other values. That is enough to start producing meaningful text output, from simple messages to generated HTML. With this orientation, we are ready to use strings as a core building block in real Python programs.