1

I want to know what is the diff between two string operations in python

filestamp = time.strftime('%Y-%m-%d')
database = "mysql";

Between this

filename = "/home/vmware/%s-%s.sql" % (database, filestamp)

and

filename = "/home/vmware/"+database+"-"+filestamp+".sql"

2 Answers 2

2

String interpolation using the '%' operators take the types of the interpolated values into account. String concatentation using the '+' will only work for strings. So you can't mix strings with numbers using the '+' operator. In general: string interpolation is what you want - at least for building strings from other values especially if you deal with different types.

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

2 Comments

If i use "+" am i committing any blunder , will my script work as expected . may be not efficent but will that cause any misfunctioning at any stage
@Mahakaal: "a" + 1 gives TypeError: Can't convert 'int' object to str implicitly. class C(object): pass, "a" + C() gives TypeError: Can't convert 'C' object to str implicitly. However, some classes may define a __radd__ method that's basically return str(self) + some_str.
0

The first approach creates 1 string where as the second creates temporary strings which is wasted. Strings in python are immutable, once created you cannot modify it.

3 Comments

i don't understand "wasted" . i mean i am using in my program and they are working. whats problem in second. i am doing database backups in loop and its working. Under which case i can be in problem if i use second case
@Mahakaal: By wasted, I mean the temporary variables created between each concatenate operation is passed to the next and discarded. Each '+' creates a string variable that is used in the next (left to right) and discarded as it is no longer referred to. It works but not efficient.
It's confusing to talk about "variables" here. There are "anonymous" string objects being created in between.

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.