Python Strings: Indexing, Slicing and Methods
A string (str) is a sequence of characters. You can write one with single quotes, double quotes, or triple quotes for text that spans several lines. 'cat' and "cat" are the same value; pick whichever lets you avoid escaping, such as "It's".
Indexing and slicing
Each character has a position, starting at 0. word[0] is the first character, and negative indexes count from the end, so word[-1] is the last. A slice word[start:stop] returns the characters from start up to, but not including, stop. Leave out start to begin at the front or stop to run to the end. Slicing never raises an error for out-of-range positions; it just returns what exists.
Strings are immutable: you cannot change a character in place. Every method that seems to modify a string actually returns a new one, so remember to assign the result.
Expected output
P n Pyt hon 6 PYTHON python padded! ['a', 'b', 'c'] 2026-11-21 True PyTHon
Methods worth memorizing
upper(),lower()andtitle()change letter case.strip()removes whitespace from both ends;lstrip()andrstrip()do one side.split(sep)breaks a string into a list of pieces. With no argument it splits on any run of whitespace.sep.join(items)is the reverse: it glues a list of strings together withsepbetween them. Note that the separator comes first.replace(old, new)substitutes every occurrence.startswith(),endswith()andfind()search without changing anything.
The in operator checks for a substring: "th" in "Python" is True. Use len() to count characters. For a full list with examples, see our Python string methods cheat sheet.
Escape sequences
Inside quotes a backslash starts an escape: \n is a new line, \t a tab and \\ a literal backslash. Prefix a string with r, as in r"C:\new", to make a raw string in which backslashes are kept as typed. Raw strings are common for Windows paths and regular expressions.
Common mistakes
- Calling
text.upper()and expectingtextto change. Writetext = text.upper(). - Off-by-one slices:
word[0:3]gives three characters, positions 0, 1 and 2. - Writing
",".joinbackwards aslist.join(","). Lists have nojoinmethod.
Summary
- Indexes start at 0; negative indexes count from the end.
s[a:b]slices fromaup to but not includingb.- Strings are immutable; methods return new strings.
split()andjoin()convert between strings and lists.
Quiz: Strings