简体   繁体   中英

method returns a string…but why?

I am just coming to grips with Python so am trying to grasp 'rules of thumb' so I can understand how the bits and pieces work together.

So for this code:

string = "Hello World"
string.replace ("World", "Mars")
print string (which would equal "Hello World")

I understand that it doesn't change the data object and in order to do that you would need to assign a variable.

hello = string.replace("World", "Mars")
print hello

I'm more wondering if returning a string is just something typical of methods. Or is there some greater underlying rule here. Because when I think about a function you can't change a data object there either unless you assign it a variable. So is this a general rule of thumb in Python? That you cannot alter an object without doing:

object = altering code

I hope all this makes sense?

Strings in Python are immutable - they can't be changed. In this sense, Python strings are much like numbers. The result of string-manipulation operators/methods has to be used.

Now, mutable objects are designed to be changed: lists and dictionaries are mutable objects - most (all standard?) side-effecting methods return None (showing that it is the mutation that is of importance).

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