Python String Formatting Efficiency: F-strings vs Format vs % Method

#PythonProgramming #CodeOptimization #EfficientCoding #OOP #dailylearning In most cases, f-strings are the fastest and most efficient way to format strings in Python. - Let us see the time taken by each method for large number of iterations, time is in seconds -> iterations = 10000000 start = timer() for i in range(iterations):     my_string12 = "The variable is %s and pi is approximately %.4f" % (var, var1) end = timer() print("Time taken by % method: ", end - start) start = timer() for i in range(iterations):     my_string13 = "The variable is {} and pi is approximately {:.4f}".format(var, var1) end = timer() print("Time taken by format() method: ", end - start) start = timer() for i in range(iterations):     my_string14 = f"The variable is {var} and pi is approximately {var1:.4f}" end = timer() print("Time taken by f-strings method: ", end - start) Output -> Time taken by % method: 4.856100000004517 Time taken by format() method: 5.290773199987598 Time taken by f-strings method: 4.271119200013345

To view or add a comment, sign in

Explore content categories