user11211747
user11211747

Reputation:

Appropriate use of python3 format function

I saw the following example of the appropriateness of the code.

for (i in 0 until stack.size)  # bad
while (!stack.isEmpty)  # good

In this perspective, What's the best code in my situation.

In Byte-of-python, the format function is said to simplify code, but I wonder if reckless use is more harmful.

START_TIME = time.time()
time.sleep(1)
END_TIME = time.time()

print("spend time : {time}".format((END_TIME - START_TIME) = 'time') 
# Why is this a grammatical error?

print("spend time : " + str(END_TIME - START_TIME ))

Upvotes: 1

Views: 45

Answers (2)

glhr
glhr

Reputation: 4537

Your print statement is missing a bracket at the end, and this is the correct syntax:

print("spend time : {time}".format(time = END_TIME - START_TIME))

Note that you can simplify this to:

print("spend time : {}".format(END_TIME - START_TIME))

Or using f-strings:

print(f"spend time : {END_TIME - START_TIME}")

Using format() or f-strings instead of string concatenation is generally preferred for readability. It also allows you to combine different data types without having to cast them to a string first.

Upvotes: 1

SyntaxVoid
SyntaxVoid

Reputation: 2633

The str.format method provides readability to code, especially when you need to insert things in the middle of strings. Imagine you want to construct a string that reads "The weather is {sun_status} today with a high of {high_temp}, a low of {low_temp}, and a {percip_chance}% chance of rain". Writing it out using string concatenation would be very ugly...

s1 = "The weather is " + sun_status + " today with a high of " + str(high_temp) + ", a low of " + str(low_temp) + ", and a " + str(percip_chance) + "% chance of rain."

The str.format method cleans this up and takes care of all the str type casting for you (if you need it)

s1 = "The weather is {sun_status} today with a high of {high_temp}, a low of {low_temp}, and a {percip_chance}% chance of rain"\
     .format(sun_status=sun_status, 
             high_temp=high_temp,
             low_temp=low_temp, 
             percip_chance=percip_chance)

There is also an error in your code. when you call the str.format method, the keyword can be whatever you placed in the curly braces {} and is not enclosed with strings. It must also come first.

print("spend time : {time}".format(time = (END_TIME - START_TIME)))

Upvotes: 1

Related Questions