0

I am calling a method on an object and I want the returned value to be assigned to the object itself. Is there a proper programming idiom for this?

The example I am using is this:

d = "2007-07-18 10:03:19"
d.split()[0]

However split doesn't change the original.


The other way:

d = d.split()[0]

Seems rather clunky. Is there a cleaner way or is this just the way it is?

1
  • That is just the way it is. Commented May 29, 2013 at 4:36

1 Answer 1

3

No, you are using a string, which is immutable, so you can't mutate its value.

Is there a proper programming idiom for this?

You are already using it, however to be more efficient you may use d=d.split(None, 1)[0] since you only need the first part, but what you are doing is sufficient anyway.

Sign up to request clarification or add additional context in comments.

1 Comment

In a bit different scenario, x=list(d) and then working with x might be sensible. I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.