How to replace a specific character in a string in Python

Published on Aug. 22, 2023, 12:15 p.m.

To replace a specific character in a string in Python, you can use the replace() method. Here is an example:

original_string = "Hello, world!"
new_string = original_string.replace(",", "-")
print(new_string)

This will replace all occurrences of the comma character , in original_string with the dash character -, and print out the new string: Hello- world!.

Note that the replace() method returns a new string object and does not modify the original string. If you want to update the original string with the new string, you can simply assign the new string back to the original string variable, like this:

original_string = original_string.replace(",", "-")

To replace a specific character in a string using regular expressions in Python

To replace a specific character in a string using regular expressions in Python, you can use the re.sub() method. Here’s an example:

import re

original_string = "Hello, world!"
new_string = re.sub(",", "-", original_string)
print(new_string)

This will use a regular expression to find all occurrences of the comma character , in original_string, and replace them with the dash character -. The re.sub() method returns the new string with the replacements applied, and the code above will print out the new string: Hello- world!.

Note that the first argument to re.sub() is the regular expression pattern to search for, the second argument is the replacement string to use, and the third argument is the original string to search and replace within.

use a list comprehension with the join()

Another way to replace a character in a string in Python is to use a list comprehension with the join() method. Here’s an example:

original_string = "Hello, world!"
new_string = ''.join(['-' if char == ',' else char for char in original_string])
print(new_string)

This code will create a new string by iterating through the characters in original_string, replacing any instance of the comma character , with a dash character -, and leaving all other characters unchanged. The result is then printed out.

Note that this method returns a new string object and does not modify the original string. If you want to update the original string with the new string, you can simply assign the new string back to the original string variable, like this:

original_string = ''.join(['-' if char == ',' else char for char in original_string])

Tags:

related content