Skip to content

Python replace character in the list | Example code

  • by

Use regex to replace characters in the list in Python. The re module in Python provides the sub() and subn() functions that can be used to replace characters in a list using regular expressions.

Example replace character in the list in Python

A simple example code removes multiple characters from a string. Removing “e”, “l’, and “p” char from the given string.

You have to import the re module for this example.

import re

print(re.sub("e|l|p", "", "Hello Python Developers"))

Output:

Python replace character in the list

Or you can iterate over the list and update the desired character at each index. Here’s an example:

def replace_character_in_list(lst, old_char, new_char):
    for i in range(len(lst)):
        if lst[i] == old_char:
            lst[i] = new_char

# Example usage
my_list = ['a', 'b', 'c', 'd']
replace_character_in_list(my_list, 'c', 'x')
print(my_list)  # Output: ['a', 'b', 'x', 'd']

Another example

import re

def replace_character_in_list(lst, pattern, replacement):
    # Convert the list to a string
    string_representation = ''.join(lst)

    # Use re.sub() to replace the characters
    modified_string = re.sub(pattern, replacement, string_representation)
    
    # Convert the modified string back to a list
    modified_list = list(modified_string)
    
    return modified_list

# Example usage
my_list = ['a', 'b', 'c', 'd']
modified_list = replace_character_in_list(my_list, r'[a-d]', 'x')
print(modified_list)  # Output: ['x', 'x', 'x', 'x']

Comment if you have any doubts or suggestions on this Python char topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *