Sobes.tech
Junior — Middle

Is it possible to replace a specific character in a string without creating a new string?

sobes.tech AI

Answer from AI

In Python, strings are immutable, so you cannot replace a character in a string "in place" without creating a new string.

If you need to change a character, you usually create a new string, for example:

s = "hello"
s = s[:1] + 'a' + s[2:]  # replace the second character with 'a'
print(s)  # 'hallo'

If you need to change individual characters frequently, you can convert the string to a list of characters, modify the element, and then join it back:

s = "hello"
lst = list(s)
lst[1] = 'a'
s = ''.join(lst)
print(s)  # 'hallo'

Thus, you cannot directly change a character in a string; a new string is always created.