Python Strings — Slicing, Methods, and f-Strings
A string is a sequence of characters, and most text work in Python is three moves on that sequence. Slice out the part you need with square brackets. Call a method such as strip, split, or replace to get a new string with the change you want. And build new text with an f-string when values belong inside a line. This guide works through each move in small programs: indexing from both ends, slicing with a step, the error that proves a string cannot be changed in place, the methods that clean and split text, a search that returns -1 when nothing matches, and f-string formats that fix decimals and padding.
Written November 12, 2026 · Tested with Python 3.12.3 · 10 min read
- The main program: length, indexing, and slicing
- Indexing: one character at a time
- Strings cannot be changed in place
- Methods: clean, split, join, and replace
Written November 12, 2026
Tested with Python 3.12.3
What this guide is
A string in Python is a sequence of characters in order. That one fact explains the whole guide. Because a string is a sequence, you can count its characters, pick one character by position, and cut out a run of characters as a slice. Because a string cannot be changed after it is built, every method that looks like an edit returns a new string and leaves the original alone. And because text is how programs talk to people, Python provides a short way to build a string from values, the f-string. The sections below take those ideas in order, using one short word as the running example so every slice can be checked by eye.
The main program: length, indexing, and slicing
s = "veldica"
print(len(s))
print(s[0], s[-1])
print(s[0:3])
print(s[3:])
print(s[:4])
print(s[::-1])
print(s[::2])
The exact output:
7
v a
vel
dica
veld
acidlev
vlia
The word has seven characters, so len returns 7. Index 0 is the first character and index -1 is the last character. A slice written s[start:stop] returns the characters from start up to, but not including, stop, so s[0:3] returns the first three characters and s[3:] returns the rest. Leaving a bound out means the nearest end of the string. A third number in a slice is a step: a step of -1 walks backwards and returns the word reversed, and a step of 2 takes every second character. The sections below take each part in turn.
Indexing: one character at a time
An index in square brackets returns the character at that position. Positions count from 0 at the left end, so the characters of "veldica" sit at indices 0 through 6. A negative index counts from the right end: -1 is the last character, -2 is the one before it, and -7 is the first character of a seven-character string. The two ends meet in the middle, so a reader can pick whichever end is nearer the character they want.
An index past either end is an error, while a slice past either end is not. Asking for s[7] on a seven-character string raises an index error, because there is no character at that position. Asking for s[0:99] returns the whole string, because a slice stops at the end it finds. That difference matters in loops and parsers: a slice is the safe form when a length is not known in advance, and a single index is the strict form when a missing character should stop the program.
Strings cannot be changed in place
A string is immutable, which means no operation changes the characters inside an existing string. Trying to assign into a position fails at once:
s = "hello"
try:
s[0] = "H"
except TypeError as e:
print("TypeError:", e)
t = "H" + s[1:]
print(t)
The exact output:
TypeError: 'str' object does not support item assignment
Hello
The assignment raises a TypeError and the string stays as it was. The working form builds a new string instead: "H" joined to the slice s[1:], which holds every character after the first, gives "Hello". Every method in the next section follows the same rule. A call such as s.upper() returns a new string and leaves s untouched, so the result must be kept, in a new name or by assigning it back to the same name. A method call written on its own line, with the result thrown away, changes nothing.
Methods: clean, split, join, and replace
String methods are called with a dot, as in s.strip(). Four groups cover most daily work. Cleaning methods trim or change case. Splitting and joining convert between a string and a list. A replacing method swaps one piece for another. And test methods answer a yes-or-no question about the text:
raw = " Hello, Veldica World "
print(repr(raw.strip()))
print(raw.strip().lower())
print(raw.strip().upper())
print("a,b,c".split(","))
print("-".join(["a", "b", "c"]))
print("hello world".replace("world", "veldica"))
print("veldica.com".startswith("veldica"))
print("veldica.com".endswith(".com"))
print("abcabc".count("bc"))
print(" pad ".strip() == "pad")
The exact output:
'Hello, Veldica World'
hello, veldica world
HELLO, VELDICA WORLD
['a', 'b', 'c']
a-b-c
hello veldica
True
True
2
True
The strip method removes spaces from both ends, and repr shows the result in quotes so the trimming is visible. The lower and upper methods return the text in one case. The split method cuts a string at each comma and returns a list of the pieces, and join does the reverse, placing its string between every pair of items in a list. Note which string join is called on: the separator is the string, and the list is the argument. The replace method returns a string with every match swapped. The last four lines are tests: startswith and endswith check the two ends, count reports how many times a piece occurs, and the final line compares a stripped string with a plain word and gets True.
Finding text: find returns -1, in returns a bool
Two search forms answer two different questions. The in operator answers whether a piece occurs at all, with True or False. The find method answers where the first match starts, and returns -1 when there is no match:
s = "Python Strings"
print(s.find("String"))
print(s.find("Java"))
print("ring" in s)
print(s.title())
print("42".zfill(5))
print("abc".isalpha(), "a1".isalpha(), "123".isdigit())
The exact output:
7
-1
True
Python Strings
00042
True False True
The word String starts at index 7, after the seven characters of "Python ". The word Java does not occur, so find returns -1 rather than raising an error; code that uses the result as an index must check for -1 first. The in check finds ring inside Strings, as a plain substring search with no word boundaries. The last three lines are small helpers that recur in input handling: title capitalizes each word, zfill pads a numeric string with zeros on the left to a fixed width, and isalpha and isdigit test whether every character is a letter or a digit.
f-strings: values inside text
A string literal that starts with f is an f-string. Inside it, braces hold an expression, and Python replaces the braces with the value of that expression when the string is built. A colon inside the braces adds a format: a fixed number of decimals, zero padding, or alignment in a fixed width:
name = "veldica"
count = 3
price = 12.5
print(f"{name} has {count} guides")
print(f"{price:.2f}")
print(f"{count:03d}")
print(f"{'left':<8}|")
print(f"{'right':>8}|")
print(f"{name!r}")
The exact output:
veldica has 3 guides
12.50
003
left |
right|
'veldica'
The first line places two values in a sentence. The format .2f prints a number with two digits after the point, which is the form money and measurements usually need. The format 03d pads an integer to three characters with zeros. The < and > formats align text to the left or the right inside a width of eight characters, and the bar after each line marks where the field ends. The !r at the end asks for the quoted form of the value, the same form repr returns, which is handy when a line must show whether spaces sit inside a value.
Joining and repeating with operators
Two operators work on strings directly. The + operator joins two strings end to end, and the * operator repeats a string a given number of times:
a = "py"
b = "thon"
print(a + b)
print(a * 3)
print("py" in "python")
print("zz" in "python")
The exact output:
python
pypypy
True
False
Joining with + suits two or three pieces. For a list of pieces, join from the methods section is the right tool, because it places a separator between the pieces and takes the whole list at once. Repetition suits short fixed marks, such as a rule line or a padding run; for text built in a loop, collecting pieces in a list and joining them once at the end is the clearer shape. The last two lines repeat the in test from the search section: py occurs at the start of python, and zz does not occur at all.
Which form for which job
| Job | Form | Why |
|---|---|---|
| Count the characters in a string | len(s) |
It returns the number of characters in the sequence |
| Take the first character, or the last | s[0], s[-1] |
Index 0 counts from the left and -1 counts from the right |
| Take a run of characters | s[start:stop] |
The slice stops before stop and tolerates a stop past the end |
| Reverse a string, or take every second character | s[::-1], s[::2] |
The third slice number is a step, and a negative step walks backwards |
| Change a character in a string | Build a new string from slices and + |
A string is immutable, so an in-place assignment raises a TypeError |
| Trim spaces and fix case | strip, lower, upper |
Each method returns a new string with the change applied |
| Turn text into pieces, or pieces into text | split, join |
split returns a list at each separator, and join reverses it |
| Find where a piece first occurs | find |
It returns the starting index, or -1 when there is no match |
| Ask only whether a piece occurs | in |
It returns True or False with no index to check |
| Put values into a line of text | An f-string | Braces hold expressions, and a colon adds decimals, padding, or alignment |
Checklist
- Before indexing a string, count from the end that is nearer: 0 from the left, -1 from the right.
- Before using a slice result, remember the stop index is left out, so
s[0:3]holds three characters, not four. - Before assigning into a string position, stop: build a new string from slices instead.
- Before writing a method call on its own line, keep its result; a discarded result means the change never happened.
- Before using a
findresult as an index, check it is not -1. - Before joining a list of pieces with
+in a loop, switch tojoinwith the separator you need. - Before printing a number inside a sentence, give its f-string a format, so decimals and padding come out fixed.
Related guides on this site
- Python Lists, Dicts, and Sets — The Three Collections You Use Every Day — the list that
splitreturns andjoinconsumes, and the other two collections that sit beside strings in daily work. - Python Functions — def, Default Arguments, and Functions as Values — the functions that take strings in, return new strings, and use f-strings to build the lines they return.
Sources
- Python Tutorial, An Informal Introduction to Python — strings, indexing, slicing, and the rule that strings are immutable.
- Python Standard Library, Text Sequence Type — str — the string methods, including strip, split, join, replace, find, and the case and test methods.
- Python Tutorial, Fancier Output Formatting — f-strings, format specifications for decimals, padding, and alignment, and the repr form.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.