Menu

Python Strings: f-Strings, Slicing, and Every String Method You'll Use

Working with text in Python — creating strings, using f-strings, slicing, and the everyday methods like split, join, replace, and strip.

Text, But With Methods

A Python string is a sequence of characters, and you'll use strings more than any other type. Every name, label, message, URL, file path, and API response lives in a string at some point.

Create one with quotes — single, double, or triple:

main.py
Output
Click Run to see the output here.

Single and double quotes are interchangeable. Use whichever keeps you from having to escape a character. "don't" is clean; 'don\'t' needs a backslash.

Strings are immutable. Once a string exists, you can't change a character of it in place. Every operation that looks like it changes a string actually returns a new one. This is why you'll write text = text.upper() rather than just text.upper() — without the reassignment, the new uppercase string would be thrown away.

Joining and Repeating

Two operators do most of the string combining you'll need:

main.py
Output
Click Run to see the output here.

+ concatenates strings. * repeats a string. Both return a new string.

Concatenating many pieces with + gets ugly fast. When you're mixing values of different types into a message, reach for f-strings instead — see the next section.

f-Strings: The Way You'll Usually Format

Put an f in front of the opening quote and the string becomes a template. Anything in {...} gets replaced with the value of that expression:

main.py
Output
Click Run to see the output here.

You can put any expression inside the braces — variables, arithmetic, method calls, function calls. Keep them simple, though; if you're tempted to cram a three-line calculation into {...}, compute it into a named variable first.

f-strings also support format specifiers after a colon, for controlling number formatting, padding, and alignment:

main.py
Output
Click Run to see the output here.

These format specs are the same ones str.format() uses and are worth a quick skim once you're comfortable with the basics. You don't need them for day-one code.

Slicing: Pick a Piece

Strings are indexable like sequences. Each character has a zero-based position, and you can grab one character or a range:

main.py
Output
Click Run to see the output here.

The pattern [start:stop:step] shows up in lists and other sequences too, so investing a few minutes to internalise it pays off everywhere.

Two things worth calling out:

  • The stop index is exclusive: word[0:2] includes indices 0 and 1, not 2.
  • Negative indices count from the end: -1 is the last character, -2 the one before, and so on.

How to Reverse a String

Strings don't have a .reverse() method — they're immutable — but slicing with a step of -1 gets the job done in one line:

main.py
Output
Click Run to see the output here.

word[::-1] reads as "from start to end, step backwards by 1." The result is a brand-new string; the original is untouched. If you need to iterate the characters in reverse without materialising a new string, reversed(word) returns a lazy iterator.

How to Check a String's Length

len(text) returns the number of characters:

main.py
Output
Click Run to see the output here.

Note that len counts Unicode code points, not bytes. len("café") is 4, not 5, even though the UTF-8 encoding takes more bytes — which is usually what you want.

How to Check If a String Contains a Substring

The in operator is the idiomatic check, and it reads like English:

main.py
Output
Click Run to see the output here.

For case-insensitive checks, normalise both sides first:

main.py
Output
Click Run to see the output here.

If you need the position, not just a yes/no, use .find() — it returns the index or -1 when the substring isn't there.

Common String Methods

Strings have dozens of methods. You'll reach for this handful constantly:

main.py
Output
Click Run to see the output here.

Splitting and joining:

main.py
Output
Click Run to see the output here.

.split(separator) turns a string into a list. separator.join(list_of_strings) glues it back together. These two methods carry a disproportionate amount of real-world string work.

One more useful pair:

main.py
Output
Click Run to see the output here.

That's a parser for a single-line config entry, written in three lines. Small strings, big leverage.

Checking What's Inside

Several methods return booleans, useful in if conditions:

main.py
Output
Click Run to see the output here.

Use these sparingly — they don't handle Unicode quirks in all the ways you might expect. For anything beyond ASCII, either lean on the regex module or the unicodedata module.

Escaping Special Characters

Some characters need a backslash to appear inside a string:

main.py
Output
Click Run to see the output here.

If you're writing Windows paths or regexes, raw strings make life easier. Put an r in front of the quote and backslashes stop being escape characters:

main.py
Output
Click Run to see the output here.

Strings Are Everywhere, So Keep It Readable

Three habits that keep string-heavy code from turning into soup:

  1. Use f-strings for interpolation. Don't chain + across multiple types.
  2. Reassign when you "mutate." text = text.strip(), not text.strip() alone.
  3. Reach for .split() and .join() before writing manual loops to parse or assemble text. They're faster, clearer, and harder to get wrong.

Next: f-strings in depth — the formatting tool you've seen a handful of times already, plus the number- and date-formatting specs that make them worth mastering.

Frequently Asked Questions

What is an f-string in Python?

An f-string is a string literal prefixed with f, where anything inside {...} is replaced with the value of that expression. Example: f"Hello, {name}!" plugs the current value of name into the string at runtime.

How do I reverse a string in Python?

Use slicing with a step of -1: reversed_text = original[::-1]. That returns a new string made of the same characters in reverse order. The original string is untouched because strings in Python are immutable.

How do I split a string in Python?

Call .split() on the string. With no argument it splits on any whitespace: "a b c".split() returns ['a', 'b', 'c']. You can pass a specific separator: "a,b,c".split(",") returns ['a', 'b', 'c'].

Are Python strings mutable?

No. Strings are immutable — once a string exists, you can't change any of its characters in place. Every method that "changes" a string actually returns a new one. This is why you see patterns like text = text.strip() — you reassign the variable to the new string.

How do I concatenate strings in Python?

Use + to join two strings: "hello" + " " + "world". For combining a value into a sentence, prefer an f-string: f"Hello, {name}". For joining many pieces from a list, use separator.join(pieces) — it's faster and reads better than chained +.

How do I check the length of a string in Python?

Call the built-in len(text). It returns the number of characters (Unicode code points), so len("café") is 4. For byte length, encode first: len(text.encode("utf-8")).

Learn to code with Coddy

GET STARTED