Why is String Formatting with % better than Concatenation


#1

String Formatting with %, Part 1

Why should i use String Formatting with %, Part 1 and not Concatenation. please give me your opinions why it was reccomended

Here is the recommended code:

string_1 = "Camelot"
string_2 = "place"

print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)

Here is the result:

Let's not go to Camelot. 'Tis a silly place.

Here is a Concatenation that will produce the same result as the one above



string_1 = "Camelot"
string_2 = "place"

print "Let's not go to " + string_1 + ". 'Tis a silly " + string_2 + "."

Let's not go to Camelot. 'Tis a silly place.


#2

It’s not really a matter of being better, just more readable and better organized.

"miles travelled, " + distance + " / time elapsed, " + elapsed_time + \
" = average speed: " + distance / elapsed_time

Compared to,

"miles travelled, %d / time elapsed, %d = average speed: %.2f" % \
(distance, elapsed_time, distance / elapsed_time)

Not to mention that it permits formatting of outputed values.

We see Python going away from the old string formatting adapted from C to the newer .format function (origin unknown to me) used in Python 3.

"miles travelled, {} / time elapsed, {} = average speed: {:.2f}".format(\
distance, elapsed_time, distance / elapsed_time)

https://pyformat.info/


#3

Thanks Roy , i may have not been patient for see the advancement of this sort of optimization in the writing and structuring of that particular code.i may have jumped the gun to soon , i can see it being applied in other area like date time also

from datetime import datetime
now = datetime.now()

print '%s/%s/%s' % (now.month, now.day, now.year)

10/27/2017

Anyway i will keep on seeking and learning until the whole puzzle fits all in.

Thanks once again.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.