How to change one character in a String with Python?

Estimated read time 2 min read

In Python, strings are immutable, which means you cannot directly change a single character within a string. However, you can create a new string with the desired change by using various string manipulation techniques. Here are a few methods you can use:

  1. Using string slicing and concatenation:
# Changing a character in a string using string slicing and concatenation
string = "Hello, world!"
index = 7  # Index of the character to be replaced
new_character = 'W'

new_string = string[:index] + new_character + string[index + 1:]

print(new_string)

In this example, the character at index 7 (which is ‘w’) is replaced with ‘W’. The original string is sliced into two parts: the portion before the index and the portion after the index. The new character is inserted between these two portions using string concatenation.

  1. Using the str.replace() method:
# Changing a character in a string using str.replace()
string = "Hello, world!"
old_character = 'w'
new_character = 'W'

new_string = string.replace(old_character, new_character)

print(new_string)

In this method, the str.replace() method is used to find all occurrences of the old character and replace them with the new character in the string.

It’s important to note that both methods create a new string with the desired change rather than modifying the original string directly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply