简体   繁体   中英

Are python strings can be mutable?

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?

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM