简体   繁体   中英

Basic python question about assignment and changing variable

Extremely basic question that I don't quite get.

If I have this line:

my_string = "how now brown cow"

and I change it like so

my_string.split()

Is this acceptable coding practice to just straight write it like that to change it? or should I instead change it like so:

my_string = my_string.split()

don't both effectively do the same thing?

when would I use one over the other?

how does this ultimately affect my code?

always try to avoid:

my_string = my_string.split()

never, ever do something like that. the main problem with that is it's going to introduce a lot of code bugs in the future, especially for another maintainer of the code. the main problem with this, is that the result of this the split() operation is not a string anymore: it's a list . Therefore, assigning a result of this type to a variable named my_string is bound to cause more problems in the end.

The first line doesn't actually change it - it calls the .split() method on the string, but since you're not doing anything with what that function call returns, the results are just discarded.

In the second case, you assign the returned values to my_string - that means your original string is discarded, but my_string no refers to the parts returned by .split() .

Both calls to .split() do the same thing, but the lines of your program do something different.

You would only use the first example if you wanted to know if a split would cause an error, for example:

try:
    my_string.split()
except:
    print('That was unexpected...')

The second example is the typical use, although you could us the result directly in some other way, for example passing it to a function:

print(my_string.split())

It's not a bad question though - you'll find that some libraries favour methods that change the contents of the object they are called on, while other libraries favour returning the processed result without touching the original. They are different programming paradigms and programmers can be very divided on the subject.

In most cases, Python itself (and its built-in functions and standard libraries) favours the more functional approach and will return the result of the operation, without changing the original, but there are exceptions.

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