GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Pricing
  • Log in
  • Sign up for free
  • Full-Stack Development
  • Front-End Development
  • Back-End Development
  • Python Development
  • HTML
  • JavaScript
  • React
  • SQL
  • CSS
  • Typescript
  • Python

This view

  • Original page
  • New address

GeezerVison is showing mimo.org — Python String replace(): Swap Substrings with count

Coding Glossary
HTMLCSSJavaScriptPythonSwiftTypeScriptSQLReactProgramming Concepts
HTMLCSSJavaScriptPythonSwiftTypeScriptSQLReactProgramming Concepts

PYTHON

Python String replace() Method: Replacing Strings in Python

replace() is a string method that replaces a string’s occurrences of a substring with another substring.

How to Use String replace() in Python

The replace() method takes the old substring, the new substring, and an optional count parameter. When present, count specifies the number of occurrences to replace.

Learn Python on Mimo

CAREER PATHPython Developer
Become a Python developer. Master Python from basics to advanced topics, including data structures, functions, classes, and error handling
Beginner friendly
COURSEPython
Start your coding journey with Python. Learn basics, data types, control flow, and more
Beginner friendly

The replace() method returns a copy of the string after replacing the substrings without changing the original string.

Python

Open in MimoOpen in Mimo
string.replace(old, new, count=-1)
  • string: The string that contains the substring to look for and replace.
  • old: The substring to look for and replace.
  • new: The substring to replace the old substring with.
  • count: An optional parameter that specifies the number of occurrences to replace. The default value (-1) replaces all occurrences.

The syntax of this method ensures clarity and flexibility, allowing developers to easily modify strings without altering the original data.

When to Use String replace() in Python

In the Python programming languages, replace() is useful for replacing characters and other substrings within strings.

Correcting User Input

You can use replace() to correct common user input errors, such as replacing incorrect characters.

Python

Open in MimoOpen in Mimo
user_input = "Ths is a tst"
corrected_input = user_input.replace("tst", "test").replace("Ths", "This")
print(corrected_input)  # Outputs: 'This is a test'

Formatting Text

The replace() method is useful for formatting text by replacing placeholders with actual values, such as in template strings.

Python

Open in MimoOpen in Mimo
template = "Dear [name], your balance is [balance]"
formatted = template.replace("[name]", "John").replace("[balance]", "$100")
print(formatted)  # Outputs: 'Dear John, your balance is $100'

Processing Logs

Log files often require modification to replace sensitive information or standardize entries. You can use replace() to update log messages:

Python

Open in MimoOpen in Mimo
log_entry = "Error: User admin failed login"
updated_log = log_entry.replace("admin", "user")
print(updated_log)  # Outputs: 'Error: User user failed login'

Examples of Using String replace() in Python

Sanitizing User Input

Web applications might use replace() to sanitize user input by replacing potentially harmful characters.

Python

Open in MimoOpen in Mimo
user_input = "<script>alert('Hello!');</script>"
sanitized_input = user_input.replace("<script>", "").replace("</script>", "")
print(sanitized_input)  # Outputs: "alert('Hello!');"

Replacing Text in Files

File processing applications often use replace() to update specific text within files.

Python

Open in MimoOpen in Mimo
document = "Visit our site at <http://oldsite.com>"
updated_document = document.replace("<http://oldsite.com>", "<http://newsite.com>")
print(updated_document)  # Outputs: "Visit our site at <http://newsite.com>"

Customizing Output Messages

Customer service applications can use replace() to personalize messages as part of macros.

Python

Open in MimoOpen in Mimo
message = "Hello [customer], your order #[order_id] is confirmed."
custom_message = message.replace("[customer]", "Alice").replace("[order_id]", "12345")
print(custom_message)  # Outputs: "Hello Alice, your order #12345 is confirmed."

Learn More About Python String replace()

Python Replacing Characters in Strings

You can also use replace() to replace single characters in a string rather than substrings.

Python

Open in MimoOpen in Mimo
text = "banana"
updated_text = text.replace("a", "o")
print(updated_text)  # Outputs: 'bonono'

Replacing Multiple Characters in Python

To replace multiple different characters in a string, you can chain multiple replace() calls or use the translate() method with a translation table.

Python

Open in MimoOpen in Mimo
text = "abc123"
updated_text = text.replace("a", "x").replace("1", "y")
print(updated_text)  # Outputs: 'xbcxy23'

trans_table = str.maketrans("abc123", "xyz456")
updated_text = text.translate(trans_table)
print(updated_text)  # Outputs: 'xyz456'

Case Sensitivity

The replace() method is case-sensitive. To perform case-insensitive replacements, you can use regular expressions with the re module.

Python

Open in MimoOpen in Mimo
import re
text = "Hello World! hello world!"
updated_text = re.sub("hello", "hi", text, flags=re.IGNORECASE)
print(updated_text)  # Outputs: 'Hi World! hi world!'

Performance Considerations

replace() works particularly well with small to medium-sized strings. For extensive text processing, however, consider using compiled regular expressions or the translate() method for better performance.

Python

Open in MimoOpen in Mimo
# Efficient for large replacements
large_text = "A" * 10000
replaced_text = large_text.replace("A", "B")
print(replaced_text)  # Outputs a string of 10000 'B's

Using replace() with Tuples

When working with tuples, you can use replace() for string elements in a tuple. However, since tuples are immutable, you will need to create a new tuple with updated elements.

Python

Open in MimoOpen in Mimo
# Replacing in tuple elements
data = ("apple", "banana", "cherry")
updated_data = tuple(item.replace("a", "o") for item in data)
print(updated_data)  # Outputs: ('opple', 'bonono', 'cherry')

String Concatenation and Replace

Combine replace() with concatenation to build a new string dynamically.

Python

Open in MimoOpen in Mimo
text = "Python is great"
new_text = text.replace("great", "awesome") + " for beginners!"
print(new_text)  # Outputs: "Python is awesome for beginners!"

Replacing Text in DataFrames

In libraries like pandas, you can use replace() on entire DataFrame columns or Series.

Python

Open in MimoOpen in Mimo
import pandas as pd
df = pd.DataFrame({"Name": ["Alice", "Bob"], "Role": ["admin", "user"]})
df["Role"] = df["Role"].str.replace("admin", "manager")
print(df)
# Outputs:
#     Name      Role
# 0  Alice   manager
# 1    Bob      user

Unicode and International Text

The replace() method supports Unicode strings, allowing easy modification of international text. Ensure proper encoding and decoding when working with non-ASCII characters:

Python

Open in MimoOpen in Mimo
text = "こんにちは世界"
updated_text = text.replace("世界", "Python")
print(updated_text)  # Outputs: 'こんにちはPython'

Appending and Modifying Strings

Combining replace() with other methods like append can streamline workflows where new values are dynamically added:

Python

Open in MimoOpen in Mimo
text = "Welcome to Python"
updated_text = text.replace("Python", "Java") + " programming!"
print(updated_text)  # Outputs: 'Welcome to Java programming!'

Using replace() with Lambda Functions

You can pair replace() with lambda expressions for efficient inline operations, especially when dealing with iterative replacements.

Python

Open in MimoOpen in Mimo
data = ["apple", "banana", "cherry"]
updated_data = list(map(lambda x: x.replace("a", "o"), data))
print(updated_data)  # Outputs: ['opple', 'bonono', 'cherry']

Compiler-Friendly Optimizations

String replacement plays a significant role in optimizing text-heavy applications during compiler operations. By pre-processing strings efficiently, compilers can enhance runtime performance.

Python

Open in MimoOpen in Mimo
source_code = "print('Hello')"
optimized_code = source_code.replace("print", "optimized_print")
print(optimized_code)  # Outputs: "optimized_print('Hello')"

Defining Functions for Replacements

Encapsulating string operations into reusable def functions simplifies workflows and ensures code reusability.

Python

Open in MimoOpen in Mimo
def replace_word(text, old, new):
    return text.replace(old, new)

print(replace_word("Welcome to Java!", "Java", "Python"))
# Outputs: "Welcome to Python!"

Using str.replace with Boolean Logic

Combine replace() with a boolean condition for customized replacements.

Python

Open in MimoOpen in Mimo
text = "Error: User failed login"
is_sensitive = True

if is_sensitive:
    text = text.replace("User", "Anonymous")
print(text)  # Outputs: 'Error: Anonymous failed login'

Join 40M+ people learning for free on Mimo

Person 1
Person 2
Person 3
40M+
CAREER PATHPython Developer
Become a Python developer. Master Python from basics to advanced topics, including data structures, functions, classes, and error handling
Beginner friendly
COURSEPython
Start your coding journey with Python. Learn basics, data types, control flow, and more
Beginner friendly

4.8 out of 5 across 1M+ reviews

Check us out on Apple AppStore, Google Play Store, and Trustpilot

  • What is Python?
  • __init__() function
  • *args and **kwargs
  • Aliases
  • and operator
  • any() function
  • argparse
  • Arrays
  • asyncio
  • Booleans
  • Break statement
  • Bytes
  • Classes
  • Closure
  • Code blocks
  • Comments
  • Conditional statements
  • Console
  • Context manager
  • Data class
  • Data structures
  • Data types
  • Data visualization
  • datetime module
  • Decorator
  • Dictionaries
  • Dictionary comprehension
  • Django
  • Docstrings
  • Dunder methods
  • Encapsulation
  • enum
  • enumerate() function
  • Equality operator
  • Error handling
  • Exception handling
  • False
  • File handling
  • Filter()
  • Flask framework
  • Floats
  • Floor division
  • For loops
  • Formatted strings
  • Functions
  • Generator
  • Globals()
  • Greater than operator
  • Greater than or equal to operator
  • If statement
  • in operator
  • Indices
  • Inequality operator
  • Inheritance
  • Integers
  • Iterator
  • JSON
  • Lambda function
  • len() Function
  • Less than operator
  • Less than or equal to operator
  • List append() method
  • List comprehension
  • List count()
  • List insert() method
  • List pop() method
  • List reverse() method
  • List sort() method
  • Lists
  • Logging
  • map() function
  • Match statement
  • Math module
  • Merge sort
  • Min()
  • Modules
  • Modulo operator
  • Multiline comment
  • Multiprocessing
  • Multithreading
  • Nested loops
  • None
  • not operator
  • NumPy library
  • OOP
  • Optional arguments
  • or operator
  • Override method
  • Package manager (pip)
  • Packages
  • Pandas library
  • Parameters
  • pathlib module
  • Pickle
  • Polymorphism
  • print() function
  • Property()
  • Protocol
  • Random module
  • range() function
  • Raw strings
  • Recursion
  • Reduce()
  • Regular expressions
  • requests Library
  • return statement
  • round() function
  • Script
  • Set comprehension
  • Sets
  • SQLite
  • String decode()
  • String find()
  • String join() method
  • String replace() method
  • String split() method
  • String strip()
  • Strings
  • Ternary operator
  • time.sleep() function
  • True
  • try...except statement
  • Tuples
  • Type casting
  • Type hints
  • uuid module
  • Variables
  • Virtual environment
  • While loops
  • yield
  • Zip function

You can code, too.

Company

Careers

Blog

Jobs

Product

App

Courses

Certifications

Glossary

Code Compilers

Building Experience

Useful

Press Kit

Imprint

Help

Terms of Use

Privacy Policy

Follow us

© 2026 Mimo GmbH

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.