Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Strings

Learn Python text: quoting, f-strings, indexing and slicing, the methods worth memorizing, and the immutability that explains all the rest.

Levels: Beginner ~15 min read

Basic

Text in Python is a string, a sequence of characters written between quotes, and Python treats it with more respect than most languages do. Indexing, slicing, iteration, and a toolbox of methods all work on it directly, with no ceremony. The one thing to internalize early is that strings never change after they are created; every operation returns a new one. Half the beginner bugs in Python are this fact being ignored.

Quotes and f-strings

Single and double quotes are interchangeable, and the practical reason to choose one is so the other can live inside your text unescaped. Triple quotes span lines, which makes them the honest container for anything shaped like a paragraph. Interpolation belongs to f-strings, an f prefix that evaluates expressions in braces, and they are almost always the right answer to putting values into text.

python fstring.py
1
2
3
4
5
name = "Nadia"
loaves = 3

greeting = f"Hello, {name}. {loaves} loaves are ready."
print(greeting)  # Hello, Nadia. 3 loaves are ready.

One prefix, and the values walk in.

Inside the braces you can put expressions, not just names: f"Total: {loaves * 45.5}" works, and a colon introduces formatting, f"{total:.2f}" for two decimals, f"{n:03d}" for zero-padded numbers. The formatting mini-language is worth an afternoon someday; the two forms above carry most days.

Indexing and slicing

Characters are reachable by position, counted from zero, and negative positions count from the end, -1 being the last character. Slicing copies a range with the pattern text[start:stop], start included, stop excluded, and either end may be omitted to mean the beginning or the end of the string.

python slicing.py
1
2
3
4
5
6
7
8
loaf = "sourdough"

loaf[0]      # "s"        first character
loaf[-1]     # "h"        last character
loaf[0:6]    # "sourdo"   positions 0 through 5
loaf[:4]     # "sour"     from the start
loaf[4:]     # "dough"    to the end
loaf[-5:]    # "dough"    last five characters

Indexing picks a character; slicing picks a run.

The stop-exclusive rule feels off by one until you see the arithmetic it buys: the length of text[2:6] is exactly 6 - 2, adjacent slices share boundaries cleanly, and loaf[:4] + loaf[4:] reassembles the original without an off-by-one in sight.

The methods worth memorizing

Strings carry their toolbox with them. These are the ones that pay rent.

Seven tools that cover most string work.

Expression

Result

Job

"Sourdough".lower()

'sourdough'

Case folding, the backbone of comparisons.

" hi ".strip()

'hi'

Trimming edges, the backbone of reading input.

"a,b,c".split(",")

['a', 'b', 'c']

Breaking text into a list.

", ".join(["a", "b", "c"])

'a, b, c'

The inverse: building text from a list.

"dough" in "sourdough"

True

Membership, no method call needed.

"no".replace("n", "tw")

'two'

Substitution, everywhere it occurs.

len("sourdough")

9

A built-in function, not a method.

Notice that ", ".join(...) is called on the separator, not the list, which feels backward to everyone at first and is simply how it is. And split() with no argument splits on any run of whitespace and discards empties, the polite way to handle text typed by humans.

Strings do not change

Assigning to a position fails: word[0] = "S" raises an error, because a string is finished when it is built. Methods that look like they modify, lower(), replace(), return new strings and leave the original untouched, which is why the beginner classic does nothing:

python immutable.py
1
2
3
4
5
6
name = "nadia"
name.upper()        # returns "NADIA"... and drops it
print(name)         # nadia, unchanged

name = name.upper()  # the correct habit
print(name)           # NADIA

Calling the method is not the same as keeping its answer.

Work some text

The example below reads a messy order line and cleans it up with the tools from this lesson. Run it, then make the classic mistake live: change line = line.strip() to just line.strip() and watch the whole downstream output go back to being messy, the exact bug immutability warns you about.

Interactive Runnable example
Edit

Ready to run.

What to notice

  • Each strip() had to be kept: on the line itself, and on every item the split produced.

  • The list comprehension cleaned each item in one expression; it gets a lesson of its own later in the path.

  • Slicing with [:9] kept the summary readable without counting characters by hand.


Quick check

If you can slice from either end without hesitating, explain why name.upper() alone changes nothing, and join a list into a sentence without looking it up, text is yours to command. Next, booleans and conditionals lets programs make decisions. When you are ready, take the Python Strings quiz.

Was this page helpful?

Mark this learning resource complete to track your learning progress.