Python Strings: Methods, Formatting, and Slicing
What you’ll learn
Section titled “What you’ll learn”- How to create strings with single, double, and triple quotes, and when each form saves you from escaping.
- How to insert values into strings with f-strings and the
str.formatmethod, including format specifiers for money and padding. - The string methods you will reach for every day:
upper,lower,strip,split,join,replace,startswith,endswith, andfind. - How slicing extracts substrings, including negative indices, omitted bounds, and steps.
- Why strings are immutable, what that means for performance and safety, and how to assemble long strings efficiently.
- The basics of text encoding with UTF-8: how to encode a string to bytes and decode bytes back to a string without raising errors.
Text handling is the work OrdersPortal does most. Order numbers, customer names, shipping addresses, and status labels are all strings, and the difference between a clean order summary and a garbled one is almost always a string mistake. This tutorial walks through the operations you will use repeatedly, with a verification step after each one so you can confirm the behavior on your own machine.
Prerequisites
Section titled “Prerequisites”- Python 3.9 or later installed. Run
python --versionto confirm the version. - A way to run the samples. Save each example as
strings_demo.pyand runpython strings_demo.py. Every complete sample prints its output. - Familiarity with variables and basic types, covered in Variables and Data Types. Strings build directly on that page’s discussion of immutable types.
Strings in Python 3 are sequences of Unicode code points, not arrays of bytes. That distinction matters when you read files or talk to network services, which is why a later step covers encoding. For now, treat a string as text you can read and edit logically, even when it contains characters from any language.
Step 1 — Create strings with single, double, and triple quotes
Section titled “Step 1 — Create strings with single, double, and triple quotes”Python treats single and double quotes the same. Pick the one that avoids escaping: if your text contains an apostrophe, wrap it in double quotes, and vice versa. Triple quotes hold multi-line text and are also the standard way to write docstrings.
# single and double quotes are interchangeablecustomer = "OrdersPortal"greeting = 'Welcome back'
# embed the other quote without escapingmessage = "It's ready"tagline = 'the "orders" platform'
# triple quotes span multiple linesreceipt = """Order #1023Customer: AcmeTotal: $42.50"""print(receipt)Run it. The expected output is the three-line receipt text printed exactly as written, including the line breaks.
Verify: run print(type(message)). It shows <class 'str'>, confirming every quote style produces the same type. Try print(len(receipt)) to see that newlines count as one character each.
Step 2 — Insert values with f-strings
Section titled “Step 2 — Insert values with f-strings”An f-string prefixes the literal with f and evaluates expressions inside curly braces. Introduced in Python 3.6, f-strings are the default way to format text because they place the value next to its label and accept format specifiers inline.
order_id = 1023amount = 42.5status = "shipped"
# expressions, format specs, and method calls all work inlineline = f"Order {order_id} for ${amount:.2f} is {status.upper()}"print(line)# Order 1023 for $42.50 is SHIPPED
# the = suffix is a handy debug shorthand added in Python 3.8print(f"{order_id=}")# order_id=1023
# alignment and width are useful for columnar reportsprint(f"{'OrdersPortal':>15}") # right-align in 15 charsThe :.2f after amount is a format specifier that fixes two decimal places, which is how you render currency. The {order_id=} form prints both the name and the value, a format that turns up constantly in logs and assertions.
Verify: change .2f to ,.2f and run again. The comma adds a thousands separator, so $1199.99 becomes $1,199.99. Then try {status!r} to see that the !r conversion applies repr, producing 'shipped' with quotes.
Step 3 — Transform and inspect with string methods
Section titled “Step 3 — Transform and inspect with string methods”Strings carry methods for case, trimming, splitting, joining, and searching. Every method returns a new string because strings are immutable; the original is never changed in place. This is the most important habit to internalize from this step.
raw = " Pending Payment "
# trimming and caseprint(raw.strip()) # 'Pending Payment'print(raw.strip().upper()) # 'PENDING PAYMENT'print(raw.strip().lower()) # 'pending payment'
# splitting a field into partsparts = raw.strip().split() # ['Pending', 'Payment']print(parts)
# joining a list back into one stringprint("-".join(parts)) # 'Pending-Payment'
# search and replacenote = "order 1023 pending"print(note.startswith("order")) # Trueprint(note.endswith("pending")) # Trueprint(note.find("1023")) # 6 (index), -1 if not foundprint(note.replace("pending", "shipped")) # 'order 1023 shipped'The split method with no argument is special: it collapses runs of whitespace and strips leading and trailing space, which makes it ideal for cleaning user input. The join method is the inverse of split, and it is the efficient way to assemble a string from many parts.
Verify: call note.index("missing"). Where find returns -1, index raises ValueError. Choose find when a missing value is normal and index when missing is a bug you want to surface.
Step 4 — Slice strings with indices and steps
Section titled “Step 4 — Slice strings with indices and steps”Slicing uses the syntax [start:stop:step]. The stop index is excluded, which is the detail that trips up the most people. Negative indices count from the end, and a negative step reverses the string.
order_no = "ORD-2026-1023"
# indices count from 0print(order_no[0:3]) # 'ORD'print(order_no[4:8]) # '2026'
# omit a bound to mean "to the end" or "from the start"print(order_no[9:]) # '1023'print(order_no[:3]) # 'ORD'
# negative indices count from the endprint(order_no[-4:]) # '1023'
# step skips characters; -1 reversesprint(order_no[::-1]) # '3201-6202-DRO'Slicing is forgiving: out-of-range bounds are clipped rather than raising an error, so order_no[100:] returns an empty string instead of crashing. This makes slicing safe for pulling the last few characters off a value of unknown length.
Verify: order_no[::2] prints every other character. Then try order_no[4:100] and confirm it returns '2026-1023' rather than erroring.
Step 5 — Use str.format for reusable templates
Section titled “Step 5 — Use str.format for reusable templates”str.format predates f-strings but remains useful when the template lives in a variable or a config file and you fill it in later. The same placeholder can be reused with different values, which f-strings cannot do because their expressions are fixed at the call site.
template = "Order {id} for ${amount:.2f} ({status})"print(template.format(id=1023, amount=42.5, status="shipped"))# Order 1023 for $42.50 (shipped)
# positional and auto-numbered fieldsprint("{} shipped to {}".format("ORD-1023", "Acme"))# ORD-1023 shipped to AcmeReach for str.format when the format string is data, not code. Reach for an f-string when the values are right there in scope, because the f-string is shorter and lets you call methods inside the braces.
Verify: store template once, then call format twice with different keyword arguments to confirm the same template yields two different summaries.
Step 6 — Encode and decode text with UTF-8
Section titled “Step 6 — Encode and decode text with UTF-8”Strings hold Unicode, but files and network sockets move bytes. Encoding converts a string to bytes, and decoding converts bytes back to a string. UTF-8 is the default and the right choice almost always.
city = "München"
# encode a string to bytesdata = city.encode("utf-8")print(data) # b'M\xc3\xbcnchen'
# decode bytes back to a stringprint(data.decode("utf-8")) # 'München'
# decoding bad bytes with strict mode raises; errors='replace' is safer for logsbad = b"price \xff unit"print(ascii(bad.decode("utf-8", errors="replace"))) # 'price \ufffd unit'Always name the encoding explicitly. The default can differ across operating systems, and naming "utf-8" makes your code behave the same on Windows, macOS, and Linux. When you cannot guarantee clean input, pass errors="replace" so a stray byte becomes a replacement character instead of an exception that stops your import job.
Verify: call "OrdersPortal".encode("ascii") and confirm it returns clean ASCII bytes. Then call "München".encode("ascii") and observe the UnicodeEncodeError, which is why UTF-8 is the safer default.
Complete working example
Section titled “Complete working example”This script builds a formatted order summary for OrdersPortal from raw input, slices and searches it, and shows encoding for an international shipping address. It ties the steps together into one runnable program.
def format_order(order_id, customer, amount, status): return f"#{order_id} | {customer} | ${amount:.2f} | {status.upper()}"
def parse_summary(summary): # split on ' | ' and drop the leading '#' fields = summary.split(" | ") order_no = fields[0][1:] # strip the '#' return { "order_no": order_no, "customer": fields[1], "amount": fields[2], "status": fields[3].lower(), }
raw_orders = [ (1023, "Acme", 42.5, "pending"), (1024, "Globex", 1199.99, "shipped"), (1025, "Initech", 7.0, "paid"),]
summaries = [format_order(o, c, a, s) for o, c, a, s in raw_orders]
for s in summaries: print(s) parsed = parse_summary(s) print(" parsed:", parsed) print(" last 4 chars:", s[-4:]) print(" has 'shipped':", s.find("shipped") != -1)
# international address, encoded for a shipping labeladdress = "Löwenstraße 12, München"print("shipping label bytes:", address.encode("utf-8"))print("label back to text:", address.encode("utf-8").decode("utf-8"))Expected output:
#1023 | Acme | $42.50 | PENDING parsed: {'order_no': '1023', 'customer': 'Acme', 'amount': '$42.50', 'status': 'pending'} last 4 chars: DING has 'shipped': False#1024 | Globex | $1199.99 | SHIPPED parsed: {'order_no': '1024', 'customer': 'Globex', 'amount': '$1199.99', 'status': 'shipped'} last 4 chars: IPED has 'shipped': True#1025 | Initech | $7.00 | PAID parsed: {'order_no': '1025', 'customer': 'Initech', 'amount': '$7.00', 'status': 'paid'} last 4 chars: PAID has 'shipped': Falseshipping label bytes: b'L\xc3\xb6wenstra\xc3\x9fe 12, M\xc3\xbcnchen'label back to text: Löwenstraße 12, MünchenTroubleshooting
Section titled “Troubleshooting”Real error messages and their fixes, drawn from the mistakes that surface when you start using strings in a real program.
AttributeError: 'str' object has no attribute 'append'— you treated a string like a list. Strings are immutable; build a new one with concatenation orjoinrather than appending.ValueError: substring not found— you calledindexon a string where the substring is absent. Switch tofindif absence is normal, or guard withinfirst.UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff— you decoded bytes that are not valid UTF-8. Passerrors="replace"orerrors="ignore", or confirm the source encoding before decoding.SyntaxError: f-string: unmatched '['— on Python 3.9 and earlier, f-strings could not contain the same quote as the delimiter or use backslashes inside braces. Use a temporary variable, or upgrade to Python 3.12+, which lifted these limits.
Common mistakes
Section titled “Common mistakes”- Calling a string method and ignoring the return value.
s.strip()does not changesin place because strings are immutable. Rebind the result:s = s.strip(). - Confusing
findwithin.findreturns an index or-1; theinoperator returns a boolean and reads better in conditions:if "shipped" in status. - Assuming
split()andsplit(" ")are the same. No-argumentsplit()collapses runs of whitespace and strips leading and trailing space;split(" ")keeps empty fields between consecutive spaces. - Forgetting the
stopindex is excluded."ORD-2026"[0:3]is'ORD', not'ORD-'. Count the end as one past the last character you want. - Using
+to assemble huge strings in a loop. Repeated concatenation copies the whole string each time, which is quadratic in the worst case. Collect parts in a list and call"sep".join(parts)once. - Comparing bytes to str. A
bytesvalue read from a file opened in binary mode is not a string; call.decode("utf-8")before comparing it to a string. - Leaving encoding to the platform default.
open(path)uses a locale-dependent encoding. Passencoding="utf-8"so your file handling is consistent across operating systems. - Building f-strings from untrusted templates. f-string syntax is not a template engine. Never build an f-string from user-supplied text and
evalit; parse the template yourself or usestr.formatwith a controlled mapping.
Next steps
Section titled “Next steps”- Learn how strings fit into Python’s text handling with Type Hints to annotate
strparameters precisely. - Move on to Dictionaries to store the parsed order fields in a real data structure.
- For repeated string patterns, see the regex tutorial.
- When you need immutable, named string-like records, continue to Tuples.
Official references
Section titled “Official references”- Python 3 — Text Sequence Type:
str— the built-in string type and its methods. - PEP 498 — Formatted String Literals (f-strings) — the f-string specification.
- Python 3 — Format String Syntax —
str.formatand format specifiers. - Python 3 — Unicode HOWTO — encoding, decoding, and UTF-8.