-2

As string is immutable,so we can't change the string so how we can insert a character at middle position?

code:

s = "hello world"
s[5] = '-'

But it gives you error as it is immutable.so,how we can resolve this problem?

  • 1
    A quick [search](https://www.google.com/search?q=are+python+strings+mutable) will give you your answer - no, strings are not mutable. – BruceWayne Oct 17 '21 at 04:28

2 Answers2

1

We know string is immutable,but we can't change values through assignment operator.so we can acheive this through string slicing:

s = s[:5]+'-'+s[6:]

so now s becomes "hello-world". so this can be done using string slicing.

0

Yes , the strings in the Python are immutable. But we can perform concatenate operation on strings.

If we want to modify string like..

S = "Hello World" S[5] = '-'

It is not possible but we can do this by slicing method

S = S[:5] + '-' + S[6:] Then the result is S = "Hello-World"