Skip to main content

How to Change Values in a String in Python

Strings in Python are immutable, meaning you cannot modify them directly. Every time you need to change a value within a string, Python creates a new string with the desired modifications. This is a common task, whether you're cleaning user input, formatting data, or transforming text in bulk.

In this guide, you'll learn multiple ways to change values in a string in Python, from simple built-in methods to powerful regular expressions. Each method includes clear examples with outputs so you can choose the right approach for your use case.

Using str.replace()

The replace() method is the most straightforward and efficient way to change values in a string. It searches for all occurrences of a specified substring and replaces them with a new substring.

s = "Hello, World! Hello, Python!"

res = s.replace("Hello", "Hi")
print(res)

Output:

Hi, World! Hi, Python!

The method replaced every occurrence of "Hello" with "Hi". The original string s remains unchanged since strings are immutable.

Limiting the Number of Replacements

You can pass an optional third argument to replace() to limit how many occurrences are replaced:

s = "apple, apple, apple"

# Replace only the first occurrence
res = s.replace("apple", "orange", 1)
print(res)

Output:

orange, apple, apple
tip

str.replace() is the best choice when you know the exact substring you want to change and don't need pattern matching.

Using split() and join()

The split() method breaks a string into a list of substrings, which you can then manipulate individually before joining them back together with join().

s = "x = 5; y = x + 3;"

# Split into words, replace matching tokens, rejoin
words = s.split()
res = " ".join(["z" if word == "x" else word for word in words])
print(res)

Output:

z = 5; y = z + 3;

How it works:

  1. s.split() breaks the string into ['x', '=', '5;', 'y', '=', 'x', '+', '3;'].
  2. The list comprehension checks each word: if it equals "x", it replaces it with "z".
  3. " ".join(...) reassembles the list into a single string.
Watch Out for Partial Matches

Unlike replace(), the split() + join() approach compares whole tokens after splitting. However, this depends entirely on your delimiter. Consider this example:

s = "fox boxing foxes"

# split() uses whitespace by default
words = s.split()
res = " ".join(["cat" if word == "fox" else word for word in words])
print(res)

Output:

cat boxing foxes

Only the exact word "fox" was replaced. "foxes" and "boxing" were left untouched because they don't match exactly. This is useful when you want whole-word replacement without regex.

Using Regular Expressions

The re module provides the most powerful and flexible approach to changing values in a string. Regular expressions let you define patterns rather than fixed substrings, enabling precise control over what gets replaced.

Basic Pattern Replacement

import re

s = "x = 5; y = x + 3;"

# Replace whole-word "x" with "z" using word boundaries
res = re.sub(r'\bx\b', 'z', s)
print(res)

Output:

z = 5; y = z + 3;
  • r'\bx\b' uses word boundary anchors (\b) to ensure only the standalone word "x" is matched and not "x" inside words like "extra".
  • re.sub() replaces all matches by default.

Case-Insensitive Replacement

import re

s = "Python is great. PYTHON is popular. python is fun."

res = re.sub(r'python', 'Java', s, flags=re.IGNORECASE)
print(res)

Output:

Java is great. Java is popular. Java is fun.

The re.IGNORECASE flag matches "Python", "PYTHON", and "python" regardless of case.

Replacing Patterns with Dynamic Values

You can pass a function as the replacement argument to re.sub() for dynamic replacements:

import re

s = "item costs 100 dollars and tax is 15 dollars"

# Double every number in the string
def double_match(match):
return str(int(match.group()) * 2)

res = re.sub(r'\d+', double_match, s)
print(res)

Output:

item costs 200 dollars and tax is 30 dollars

Each numeric match is passed to double_match(), which doubles the value and returns the replacement string.

Using String Concatenation and Slicing

When you know the exact position of the value you want to change, string slicing offers a direct approach:

s = "Hello, World!"

# Replace characters at index 7 through 11 ("World") with "Python"
res = s[:7] + "Python" + s[12:]
print(res)

Output:

Hello, Python!

How it works:

  1. s[:7] extracts "Hello, ".
  2. "Python" is the new value.
  3. s[12:] extracts "!".
  4. Concatenation produces the final result.
note

This method is useful for index-based replacements, but it can be error-prone if the string length varies. Prefer replace() or regex for content-based replacements.

Using str.translate() for Character-Level Replacements

When you need to replace individual characters (not substrings), str.translate() combined with str.maketrans() is highly efficient, especially for bulk character swaps.

s = "Hello, World!"

# Replace 'H' -> 'J', 'o' -> 'a', '!' -> '?'
table = str.maketrans({'H': 'J', 'o': 'a', '!': '?'})
res = s.translate(table)
print(res)

Output:

Jella, Warld?

translate() processes the entire string in a single pass, making it faster than chaining multiple replace() calls for character-level changes.

Comparison of Methods

MethodBest ForHandles PatternsPerformance
str.replace()Simple, exact substring replacement⚡ Fast
split() + join()Whole-token replacementModerate
re.sub()Pattern-based or complex replacementsModerate
String slicingPosition-based replacement⚡ Fast
str.translate()Single-character bulk replacement⚡ Fast

Conclusion

Python provides several ways to change values in a string, each suited to different scenarios:

  • Use str.replace() for quick, straightforward substring replacements. It's the go-to method for most cases.
  • Use split() and join() when you need to manipulate individual words or tokens.
  • Use re.sub() when you need pattern matching, word boundaries, case-insensitive matching, or dynamic replacements.
  • Use string slicing when you know the exact position of the text to replace.
  • Use str.translate() for efficient single-character swaps across the entire string.

Since strings are immutable in Python, all of these methods return a new string and the original is never modified. Choose the approach that best balances readability, precision, and performance for your specific task.