The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Python string manipulation uses str methods and operators to inspect, select, change, split, combine, and format text. A string is immutable: operations such as replace() return a new string rather than editing the original. The examples below cover the common tasks and show when to use text methods, formatting, or byte conversion.
Start with Python’s immutable strings
Python’s documentation describes strings as “immutable sequences of Unicode code points.” That means a string represents text, and its contents cannot be changed in place. A method call produces a result; assign that result if you want to keep it.
message = "Hello, world!"
updated = message.replace("world", "Python")
print(message) # Hello, world!
print(updated) # Hello, Python!
For the exact semantics of string operations, see the Python built-in types reference.
Select characters or a section of text
Indexing selects one character, and slicing selects a portion. Indexes start at zero; a negative index counts from the end. In a slice, the start is included and the stop is excluded.
#1 Best Overall
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[1:4]) # yth
print(word[:2]) # Py
print(word[2:]) # thon
Because strings are immutable, an expression such as word[0] = "J" does not change the first character. Build a new string instead, for example with slicing and concatenation: "J" + word[1:].
Find text and check boundaries
Use in for a simple yes-or-no containment test. Use find() when you need the position but want a missing match represented by -1. Use index() when a missing match should raise an exception. These searches are literal and case-sensitive.
text = "Python strings"
print("strings" in text) # True
print(text.find("strings")) # 7
print(text.find("missing")) # -1
print(text.startswith("Py")) # True
print(text.endswith("ings")) # True
startswith() and endswith() test the beginning and end of a string without requiring a full search. For the behavior of each method, consult the built-in types reference.
Replace text and remove unwanted edges
Replace a literal substring
replace(old, new) returns a string with occurrences of the literal old substring replaced. It does not modify the source string, and it is not a pattern-matching operation.
Rank #2
filename = "report final.txt"
clean_name = filename.replace(" ", "_")
print(clean_name) # report_final.txt
Trim edge characters
strip(), lstrip(), and rstrip() remove characters from both ends, the left end, or the right end respectively. Their argument is a set of characters, not a literal substring to remove as a unit. With no argument, they remove surrounding whitespace.
value = "xxdataxy"
print(value.strip("xy")) # data
That call removes any leading or trailing x or y characters until it reaches a different character.
Remove a known prefix or suffix
When the goal is to remove one exact prefix or suffix, use removeprefix() or removesuffix(). Like other string methods, each returns a new string.
path = "draft-report.txt"
print(path.removeprefix("draft-")) # report.txt
print(path.removesuffix(".txt")) # draft-report
Split a string into pieces and join pieces together
split() divides a string into a list; join() combines an iterable of strings using the string before the method as a separator. They are useful in opposite directions.
line = "red,green,blue"
colors = line.split(",")
print(colors) # ['red', 'green', 'blue']
rejoined = " - ".join(colors)
print(rejoined) # red - green - blue
Calling split() without a separator splits on runs of whitespace. The separator in join() can be empty if the pieces should run together, or any other string. Every item passed to join() must be a string.
Build output from many fragments
For a known collection of fragments, collect strings and join them rather than repeatedly modifying a string in a loop.
parts = ["Name: ", "Ada", "; role: ", "engineer"]
result = "".join(parts)
print(result) # Name: Ada; role: engineer
For code that writes fragments incrementally, Python also provides io.StringIO as an in-memory text stream. The built-in types documentation covers string construction and methods.
Change case or translate characters
Use case conversion when the task is genuinely about letter case: lower() makes a lowercase form and upper() makes an uppercase form. For caseless matching, casefold() is intended for that purpose; it may make more changes than a simple lowercase conversion. Case conversion alone should not be treated as a complete solution for every locale-sensitive language task.
label = "Python"
print(label.lower()) # python
print(label.upper()) # PYTHON
print("Straße".casefold()) # strasse
For a character-by-character mapping, use maketrans() to define substitutions and translate() to apply them.
table = str.maketrans({"-": " ", "_": " "})
print("first_name-last-name".translate(table))
# first name last name
Format output with f-strings or str.format()
Formatting inserts values into an output string. For straightforward interpolation, an f-string is usually the clearest option. Put an expression in braces, with the f prefix before the quoted string.
name = "Ada"
count = 3
message = f"{name} has {count} messages."
print(message) # Ada has 3 messages.
str.format() is another supported way to fill replacement fields:
message = "{} has {} messages.".format(name, count)
Formatting creates output text; it is distinct from replace(), which substitutes a literal substring in existing text. F-strings were introduced in Python 3.6, and Python 3.12 removed many earlier restrictions on expressions inside them. If code must run on an older Python version, check that version’s syntax support. The Python lexical analysis reference documents string prefixes and f-string syntax.
Best Value
Use the right string-literal syntax for quotes and backslashes
Single and double quotes delimit ordinary string literals. Triple-quoted strings can retain newlines, and escape sequences such as n have special meanings. A raw-string prefix suppresses most escape processing, which is useful when backslashes should be represented literally.
single = 'It's text'
double = "It's text"
multiline = """First line
Second line"""
raw_path = r"folderfile.txt"
print(raw_path) # folderfile.txt
Raw strings still have syntax rules—for example, a raw string literal cannot end with an odd number of backslashes. See the language reference on lexical analysis for literal and escape details.
Keep text (str) separate from bytes
str is for text; bytes is for byte data. Decode bytes with the correct encoding to obtain text, and encode text when bytes are required by a file format, network protocol, or other binary interface. Make the encoding explicit when it is known.
raw = b"cafxc3xa9"
text = raw.decode("utf-8")
print(text) # café
encoded = text.encode("utf-8")
print(encoded) # b'cafxc3xa9'
Calling str(raw) does not decode the byte contents; it produces an informal representation of the bytes object. Choose conversion based on whether the value is text or binary data. The Python built-in types reference documents both types and their conversions.
Free tools Windows power users keep installed
One-click scans. No signup required.
Quick Recap
Choose a method, a pattern, or formatting based on the job
- Literal change: use
replace()when the target text is an exact substring. - Pattern-oriented processing: use Python’s
remodule when matching rules or patterns are needed; ordinary string methods handle literal tasks. See the regular expression library reference. - Display output: use an f-string or
str.format()to place values into a template. - Caseless comparison: use
casefold()when caseless matching is the goal, rather than assuminglower()covers every case. - Many fragments: use
join()for a collection, orio.StringIOwhen code writes incrementally. - Binary input or output: decode bytes to text or encode text to bytes with the appropriate encoding.
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.




