Home > OS >  Are python strings can be mutable?
Are python strings can be mutable?

Time:10-17

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?

CodePudding user response:

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.

CodePudding user response:

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"

  • Related