What is the output of following Python Code? s = "immutable" s[1] = 'n' print(s)

Опубликовано: 24 Сентябрь 2026
на канале: Ahmed EL-Mutasim Mohammed
1

What is the output of following Python Code?

s = "immutable"
s[1] = 'n'
print(s)

The given code will raise an error because strings in Python are immutable. You cannot change individual characters in a string directly. But you may fix that

To fix this, you can create a new string with the desired modification. Here's the corrected code:

```python
s = "immutable"
s = s[:1] + 'n' + s[2:]
print(s)
```

The output will be:

inmutable
```
Let's break down the corrected code step by step:

1. Initialization:
We start with the string `s` containing the word "immutable".
`s = "immutable"`

2. Modification:
To change the second character (at index 1) from 'm' to 'n', we create a new string.
We slice the original string into three parts:
The first part: `s[:1]` gives us the substring "i" (up to index 1, excluding index 1).
The middle part: `'n'` is the character we want to insert.
The last part: `s[2:]` gives us the substring "mutable" (from index 2 onwards).
We concatenate these three parts to form the modified string.
`s = s[:1] + 'n' + s[2:]`

3. Printing the Result:
Finally, we print the updated string.
`print(s)` will output "inmutable".

And that's it! The corrected code ensures that we replace the 'm' with 'n' in the word "immutable".