You are currently viewing Python Replace Character in String

How to replace a character in a string in Python? To replace a character in a string using Python, you can utilize the str.replace() method. This method takes two arguments, the old character you want to replace and the new character you want to use. This function replaces all occurrences of a specific substring (which can be a single character) with another substring. Keep in mind that strings in Python are immutable, so the str.replace() method returns a new string with the replacement.

Advertisements

You can replace a character in a string in Python using many ways, for example, by using the string.replace(), slicing, for loop, list(), and re.sub() functions. In this article, I will explain how to replace a character in a string by using all these methods with examples.

1. Quick Examples of Replacing Character in String

If you are in a hurry, below are some quick examples of how to replace a character in a string.


# Quick examples of replacing character in string

# Initialize the string
string = "welcome to sparkbyexamples"

# Example 1: Using string.replace() method
# Replace character in a string 
result = string.replace("w", "W")

# Example 2: Using slicing method
# Replace a character in a string 
index = 0
new_character = 'W'
result = string[:index] + new_character + string[index+1:]

# Example 3: Using list data structure 
# Replace a character in a string 
index = 0
new_character = 'W'
temp = list(string) 
temp[index] = new_character
result = "".join(temp)

# Example 4: Using re.sub() method
# Replace character in string 
result = re.sub('w', 'W', string)

# Example 5: Using for loop
# Replace character in string
old_char = "w"
new_char = "W"
result = ""
for char in string:
    if char == old_char:
        result += new_char
    else:
        result += char

2. Replace Character in String Using string.replace() Method

You can replace a specific character with a new character in the string using the string.replace() method. For example, first, you can initialize a string variable string with the value "welcome to sparkbyexamples" and then apply the replace() method over the given string to replace all occurrences of the lowercase letter 'w' with the uppercase letter 'W'. The modified string is stored in the result variable.


# Initialize the string
string = "welcome to sparkbyexamples"
print("Original string:",string)

# Using string.replace() method
# Replace character in a string 
result = string.replace("w", "W")
print("The string after replacing a character with new one:\n", result)

Yields below output.

python replace character string

3. Replace Character in String Using Slicing Method

To replace a character in a string use the slicing method. For example, you can initialize a string variable string with the value "welcome to sparkbyexamples" and then specify the index of the character you want to replace using the variable index. In this case, you’ve set index it to 0, which corresponds to the first character ‘w’ in the string.

You can define the new character that you want to replace the original character with, using the variable new_character. In this case, it’s ‘W’. You can construct the modified string using slicing. The expression string[:index] extracts the substring from the beginning of the string up to (but not including) the character at the specified index. Then, you can concatenate the new character and the remaining part of the original string using string[index+1:]. The resulting modified string is stored in the variable result.


# Initialize the string
string = "welcome to sparkbyexamples"
print("Original string:",string)

# Using slicing method
# Replace character in string 
index = 0
new_character = 'W'
result = string[:index] + new_character + string[index+1:]
print("The string after replacing a character with new one:\n", result)

Yields the same output as above.

4. Replace Character in String Using List

To replace a character in a string, you can utilize the list datatype and then convert the modified list back into a string. For example, first, you can initialize a string variable string with the value "welcome to sparkbyexamples". And then specify the index of the character you want to replace using the variable index. In this case, you’ve set the index to 0, which corresponds to the first character ‘w’ in the string.

You can define the new character that you want to replace the original character with, using the variable new_character. In this case, it’s ‘W’. You convert the string to a list by using list(string). This creates a list where each element is a character from the original string. You modify the character at the specified index in the list by assigning new_character to temp[index]. You convert the modified list back to a string using the join() method, which concatenates all the elements of the list into a single string. The resulting modified string is stored in the variable result.


# Initialize the string
string = "welcome to sparkbyexamples"
print("Original string:",string)

# Using list data structure 
# Replace character in string 
index = 0
new_character = 'W'
temp = list(string) 
temp[index] = new_character
result = "".join(temp)
print("The string after replacing a character with new one:\n", result)

Yields the same output as above.

5. Using re.sub() Method

To replace characters in a string, you can utilize the method from the (regular expression) module. For example, first initialize a string variable string with the value "welcome to sparkbyexamples". Then use the re.sub() function to replace all occurrences of the lowercase letter ‘w’ with the uppercase letter ‘W’. The first argument to provide is the pattern to search for (in this case, the lowercase ‘w’), the second argument is the replacement string (‘W’ in this case), and the third argument is the input string (string). The resulting modified string is stored in the variable result.

Using the re.sub() method is a powerful way to perform more complex replacements based on regular expressions in strings.


import re

# Initialize the string
string = "welcome to sparkbyexamples"
print("Original string:",string)

# Using re.sub() method
# Replace character in string 
result = re.sub('w', 'W', string)
print("The string after replacing a character with new one:\n", result)

Yields the same output as above.

6. Replace Characters in String Using For Loop

You can use a for loop to replace a specific character in a string. For example, first, you can initialize a string variable string with the value "welcome to sparkbyexamples". Then define the old character you want to replace (old_char) and the new character you want to replace it with (new_char). You can initialize an empty string result where the modified string will be constructed.

Use a for loop to iterate through each character in the string. Inside the loop, you check if the current character (char) is equal to the old_char. If it is, you can append the new_char to the result string; otherwise, you can append the current character unchanged. After the loop is complete, the result string will contain the modified string with the character replacements.


# Initialize the string
string = "welcome to sparkbyexamples"
print("Original string:",string)

# Using for loop
# replace charater in string
old_char = "w"
new_char = "W"
result = ""
for char in string:
    if char == old_char:
        result += new_char
    else:
        result += char
print("The string after replacing a character with new one:\n", result)

Yields the same output as above.

Conclusion

In this article, I have explained some of the Python methods like string.replace(), slicing, for loop, list() and re.sub() functions and using these functions how we can replace the character of a string with new characters.

Happy Learning !!