Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s str methods and operators to inspect, select, change, split, combine, and format text. Strings are immutable, so operations such as replace() return a new string rather than changing the original; assign the result if you want to keep it.

text = "Hello, Python!"
updated = text.replace("Python", "world")

print(text)     # Hello, Python!
print(updated)  # Hello, world!

This guide covers common operations on text strings (str) and explains when the job instead calls for bytes or pattern matching.

How do Python strings work?

A Python string is text: the built-in str type represents an immutable sequence of Unicode code points. “Immutable” means you cannot edit a string in place. A method or operator that transforms text produces a new string.

For example, text.upper() returns an uppercase version, but text remains unchanged unless you assign the result:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
text = "Good morning"
text = text.upper()
print(text)  # GOOD MORNING

Python strings can contain Unicode text, including characters beyond basic English letters. The official Python built-in types reference documents string behavior and methods.

How do you select part of a string?

Index one character

String positions start at zero, so index 0 selects the first character. Negative indexes count from the end:

word = "Python"
print(word[0])   # P
print(word[-1])  # n

An index outside the string’s range raises an IndexError.

Slice a range

A slice uses string[start:stop]: it includes the character at start and stops before stop. Either bound may be omitted; a third value sets the step.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
word = "Python"
print(word[0:2])  # Py
print(word[2:])   # thon
print(word[:3])   # Pyt
print(word[::2])  # Pto

How do you search or check a string?

Use in for a simple containment test, startswith() or endswith() for boundaries, and find() or index() when you need a position.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
message = "Python string methods"
print("string" in message)                 # True
print(message.startswith("Python"))       # True
print(message.endswith("methods"))        # True
print(message.find("string"))             # 7
print(message.find("Java"))               # -1

find() returns the first matching position, or -1 if there is no match. Use index() when a missing match should be treated as an error: it returns the position when found and raises ValueError otherwise.

message.index("string")  # 7

How do you replace or remove text?

Replace literal text

replace(old, new) substitutes occurrences of the literal old text and returns the result. It does not use regular-expression syntax.

line = "red, green, red"
cleaned = line.replace("red", "blue")
print(cleaned)  # blue, green, blue

Trim characters from the ends

strip() removes whitespace at both ends by default; lstrip() and rstrip() affect only the left or right end. If you provide characters, Python removes any of those characters from the ends, not a whole substring.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
text = "  hello  "
print(text.strip())       # hello
print("xyhelloyx".strip("xy"))  # hello

For a specific prefix or suffix, use removeprefix() or removesuffix():

filename = "report.txt"
print(filename.removesuffix(".txt"))  # report

How do you split and join strings?

Split text into pieces

split() returns a list of strings. Without an argument, it splits on runs of whitespace; with a separator, it splits at that exact separator.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
sentence = "one two   three"
print(sentence.split())  # ['one', 'two', 'three']

csv_line = "red,green,blue"
print(csv_line.split(","))  # ['red', 'green', 'blue']

Join pieces with a separator

Call join() on the separator string. Each item in the iterable must be a string.

parts = ["2026", "10", "05"]
print("-".join(parts))  # 2026-10-05

For a small number of values, an f-string can be clearer. When assembling many fragments, collect them and join once; for incremental writing, Python’s io.StringIO provides a text buffer. The built-in types reference covers string methods and construction from fragments.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do you change letter case or translate characters?

Use lower() and upper() for ordinary case conversion. For caseless matching, casefold() is designed to produce text suitable for more aggressive case-insensitive comparisons.

name = "Python"
print(name.lower())     # python
print(name.upper())     # PYTHON
print("Straße".casefold())  # strasse

Case conversion is not a universal solution for every language-sensitive comparison. Use it for the text task you intend, rather than assuming that all languages have identical casing rules.

For character-by-character substitutions or deletions, create a translation table with maketrans() and apply it with translate():

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
table = str.maketrans({"-": " ", "_": " ", "!": None})
print("hello-world!".translate(table))  # hello world

How do you format a string with values?

For straightforward interpolation, use an f-string: put an expression in braces inside a string prefixed with f.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
name = "Ada"
score = 9.5
print(f"{name} scored {score}")  # Ada scored 9.5

F-strings were introduced in Python 3.6. The Python 3.12 language reference records changes that permit many expressions previously restricted inside replacement fields; keep syntax compatible with the Python version your program targets. The Python lexical analysis reference documents string prefixes and f-string syntax.

str.format() is another supported option, useful when you want placeholders in a template:

template = "{name} scored {score}"
print(template.format(name="Ada", score=9.5))

Formatting assembles output from values; it is different from replace(), which substitutes literal text in an existing string.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do you handle quotes, backslashes, and multiline strings?

Ordinary string literals can use single or double quotes. A backslash introduces escape sequences such as n for a newline; triple quotes allow a literal to span lines. A raw-string prefix suppresses most escape processing, which is useful when backslashes should be retained.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
single = 'It's Python'
double = "It's Python"
multiline = """first line
second line"""
path = r"C:\Users\Ada"

Raw strings still have syntax rules—for example, a raw string cannot end in an odd number of backslashes. See the official language reference on string literals and prefixes for escape and prefix details.

When should you use bytes instead of strings?

Use str for text and bytes for binary data. Convert explicitly at the boundary: decode bytes using the correct encoding to obtain text, and encode text to produce bytes.

raw = b"cafxc3xa9"
text = raw.decode("utf-8")
print(text)  # café

encoded = text.encode("utf-8")

Calling str() on bytes without an encoding produces their representation, not decoded text. Decode or encode explicitly so the intended character encoding is clear.

When should you use regular expressions?

Use ordinary string methods for literal tasks such as replacing a known substring, trimming ends, or splitting on a fixed delimiter. If the operation depends on a pattern rather than exact literal text, Python’s re module provides regular-expression tools; consult the official regular-expression reference for its syntax and behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which string operation should you choose?

Need Use Key behavior
Select characters or a range Indexing or slicing Indexes begin at zero; slice stop is excluded.
Check for literal text in, startswith(), endswith() Returns a Boolean result.
Find a literal’s position find() or index() find() returns -1 when absent; index() raises ValueError.
Substitute literal text replace() Returns a new string; it is not a pattern matcher.
Divide and recombine text split() and join() join() is called on the separator.
Prepare text for case-insensitive comparison casefold() Designed for caseless matching; locale-specific requirements may need additional care.
Insert values into displayed output F-string or str.format() Formats values rather than searching and replacing literal text.
Handle binary input or output decode() or encode() Specify the appropriate encoding at the conversion boundary.
Match a text pattern re module Use the regular-expression reference for pattern-specific behavior.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.