Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
In Development Last updated: September 20, 2023
Share on:
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

This tutorial covers the different ways to replace the character in a Python string: using built-in string methods, regular expressions, and more.

Strings in Python are built-in data structures that store a sequence of Unicode characters. Unlike some Python data structures, such as lists and dictionaries, strings are immutable. Meaning you cannot modify an existing string.

However, you may want to manipulate strings—remove leading and trailing white spaces, change capitalization, replace a character with another, and much more—when working with them.

So, how do we manipulate Python strings? And how do we replace a character in a Python string? We’ll answer these questions in this tutorial focusing on:

  • Immutability of Python strings 
  • Python string methods for string manipulation 
  • Different ways to replace a character in a string 

Let’s get started…

Immutability of Python Strings

As mentioned, Python strings are immutable. So you cannot modify an existing string in place. you cannot modify an existing string in place 

For example, consider the string “Python programming!”.

You can access a single element of the string using the index and a substring by specifying the slice with the start and end, as shown:

>>> my_str = "Python programming!"
>>> my_str[0]
'P'
>>> my_str[4]
'o'
>>> my_str[1:9]
'ython pr'
>>> my_str[9]
'o'

Say you want to replace the letter ‘o’ with the digit ‘0’.

You know that you have an o at indexes 4 and 9 (see the code snippet above). But if you try to directly set the character—at the specific index—to ‘0’, you’ll get the following error:

>>> my_str[4] = '0'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Python provides a set of string methods that act on an existing string and return a new string with the required changes.

Also read: Python Programs on String Operations.

So, you can use the string methods coupled with list comprehensions, loops, and regular expressions to perform string manipulation tasks. In this tutorial, we’ll look at the different ways to replace a character in a Python string.

Replacing a Character in Python Strings

There are many use cases in which you may want to replace characters or substrings in a Python string. Here are some of them:

  • Text cleaning: When working with text data, you may need to clean the text by replacing certain characters. For example, removing or replacing special characters, extra white space, or unwanted symbols.
  • Formatting: You might want to change the formatting of text, such as capitalizing or converting text to lowercase. For instance, ensuring consistent capitalization in titles or headings.
  • Data masking: You’ll often need to mask sensitive information like personal identification numbers or credit card numbers to protect sensitive data while preserving the format.
  • URLs and Path Handling: When working with URLs or file paths, you may need to replace certain characters to ensure they are properly formatted and compatible with web browsers or file systems.

We’ll take a simple example of replacing a character in a string.

replace-char-in-string

We’ll start with an approach that uses loops and conditional statements, then proceed to discuss other better methods to achieve the same.

Let’s take the same example of replacing ‘o’ with ‘0’ in the string “Python programming!”.

Here’s how we can loop through the string using a for loop and replace the specific character:

original_string = "Python programming!"
new_string = ""
for char in original_string:
    if char == "o":
        new_string += "0"
    else:
        new_string += char
print(new_string)  

In this approach, we manually loop through each character in the original_string. If the character is ‘o’, we append ‘0’ to new_string; otherwise, we append the same character. This way, we perform character replacement and build the new_string.

# Output
Pyth0n pr0gramming!

Using for loop and conditional branching with if statements is hard to maintain. Especially when you need to replace a substring or multiple characters.

There are better approaches to replacing characters or a substring, and we’ll look at them in the following sections.

replace

#1. Using str.replace()

We can use the string method replace() to replace a character or a substring with another string. Using str.replace(old, new) replaces all occurrences of the old character or substring with the new character or substring.

Here we use the replace() method letter ‘o’ with the digit ‘0’ in the original_string.

original_string = "Python programming!"
new_string = original_string.replace("o", "0")
print(new_string) 

The resultant string is in new_string.

# Output
Pyth0n pr0gramming!

#2. Using List Comprehension and the join() Method

To replace a character in a Python string, we can use list comprehension in conjunction with the string method join().

Let’s see how we can rewrite our example:

  • We can use a list comprehension to iterate over each character in original_string. If the character is ‘o’, we replace it with ‘0’ and keep the same character otherwise. 
  • Then, we use str.join() to combine these characters into a single string, resulting in new_string. Note that this is a more concise alternative to looping and conditional branching when you need to replace a single character in a string.
original_string = "Python programming!"
new_string = ''.join(['0' if char == 'o' else char for char in original_string])
print(new_string) 

We get the expected output:

# Output
Pyth0n pr0gramming!

#3. Using Regular Expressions

Another method to replace characters in Python strings is using regular expressions (regex). Python comes with the built-in re module for regular expression matching operations. With regex, you can specify a pattern to search for, a string to search through, and a string to replace the matched pattern with.

Here, we use the sub() function from the re module with the syntax re.sub(pattern, replacement, string).

import re

original_string = "Python programming!"
new_string = re.sub(r'o', '0', original_string)
print(new_string) 

The pattern r'o' matches all occurrences of the letter ‘o’ in original_string and replaces them with ‘0’.

# Output
Pyth0n pr0gramming!

You can use regular expressions to match more complex patterns. Let’s take the example of masking credit card numbers. Say we want to replace all numbers—except the last four digits—with an ‘X’. Here’s how we can do it:

import re

def mask_credit_card(card_number):
    # Use regular expressions to match and replace characters
    masked_number = re.sub(r'\d(?=\d{4})', 'X', card_number)
    return masked_number

# Example usage:
credit_card_number = "1234567898765432"
masked_number = mask_credit_card(credit_card_number)
print(masked_number)

And here’s the output:

# Output
XXXXXXXXXXXX5432

To keep the regex simple, we haven’t included the hyphen, but if you’d like you can modify the example as needed.

#4. Using str.maketrans() and str.translate()

The str.maketrans() and str.translate() methods in Python are used to perform character-level translation and replacement in strings.

How str.maketrans() Works

The maketrans() method is used to create a translation table that specifies how characters should be replaced in a string. You can use it with the syntax:  str.maketrans(x, y). Here:

  • x is the string containing characters that you want to replace.
  • y is the string containing characters that you want to replace x with.

The maketrans() method generates a translation table based on the mappings from x to y. You can then use this translation table with the str.translate() method to perform the actual replacement.

How str.translate() Works

You can use the str.translate() method to apply the translation table created by str.maketrans() to a string. It performs character-by-character replacement based on the mappings defined in the translation table. And returns a new string with the specified character replacements applied.

Here’s how you can use the translate() method:

new_string = original_string.translate(translation_table)
  • original_string: The input string you want to modify.
  • translation_table: The translation table created using str.maketrans() that defines the character mappings.

Combining both the maketrans() and str.translate() methods, let’s rewrite our example like so:

original_string = "Python programming!"
translation_table = str.maketrans('o', '0')
new_string = original_string.translate(translation_table)
print(new_string)

Here, we create a translation table using str.maketrans('o', '0') to specify that ‘o’ should be replaced by ‘0’. We then use the translate() method on the original_string to apply this translation, resulting in new_string.

# Output
Pyth0n pr0gramming!

 These methods are useful for tasks like replacing a character and other character-level manipulation in strings.

Conclusion

Let’s review what we have learned.

Python strings are immutable. So when you want to replace a character in a Python string, you cannot just reassign the character at a particular index. We went over the following approaches to replace a character or multiple characters in a Python string:

  • Use str.replace(old, new) to replace all instances of old with new substring.
  • You can also use list comprehension and the join() method. Use list comprehension to achieve character replacement and the join() method to join the list of characters into a string.
  • You can use pattern matching with regular expressions to replace occurrences of a character or a pattern. Use the sub() function with re.sub(pattern, replacement, string).
  • Use str.maketrans() to get a translation table and the translate() method to apply the translation table to the original string.

Be sure to code some examples to understand these techniques better. Next, learn how to remove the last character from a Python string.

  • Bala Priya C
    Author
    Bala Priya is a developer and technical writer from India with over three years of experience in the technical content writing space. She shares her learning with the developer community by authoring tech tutorials, how-to guides, and more…. read more
  • Narendra Mohan Mittal
    Editor

    Narendra Mohan Mittal is a Senior Digital Branding Strategist and Content Editor with over 12 years of versatile experience. He holds an M-Tech (Gold Medalist) and B-Tech (Gold Medalist) in Computer Science & Engineering.


    read more
Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.
    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder