简体   繁体   中英

Why does this work if strings are immutable?

For this code (python):

name = input("please enter your name")

introStatement = "please take a seat"

if name != "":

    introStatement = (name) + " please take a seat"

print(introStatement) 

I was expecting a TypeError, but the program was able to print a given name and the intro statement, I thought that strings were immutable so we wouldn't be able to do this.

Any explanation would be greatly appreciated, Thank you

This is happening because you aren't modifying the name or the original introStatement.

How Python works behind the hood is that it (sort of) creates a new "array" and copies "name" and " please have a seat" to the new array. Thus, the original string isn't amended, but rather, a new one is made.

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