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:
- 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.
- Using the
# 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.