+ 1
Why is there 2 methods for string formatting with different sets of format characters?
Case 1 : Method 1 print("{0:b}".format(15)) Output: 1111 Case 1 : Method 2 print("%b"%(15)) ValueError: unsupported format character 'b' Case 2 : Method 1 print("%c"%('a')) Output: a Case 2 : Method 2 print("{0:c}".format('a')) ValueError: unknown format code 'i' for object of type 'int'
7 Réponses
+ 7
As of Python 3.6 there are more three ways to do string formatting. They added f"{my_value}". It works the same as the format method but is more succinct.
To answer your question though, the format method was added because it's a bit more useful and has a couple more features than the older method ("%d" % num). The older method was meant to be more compatible with C style string formatting. The new method was added to make string formatting cleaner and keep the language competitive. The reason all three exist is because removing features is challenging. When you remove something everyone has to update their code and that is a challenge.
+ 2
my_var = 9001
f"my power level is {my_var}"
+ 1
what's the 3rd method?
+ 1
@Arun, it only works in Python 3.6 and higher
0
What's the third method
0
See my previous comment for the third method...
0
x = 2
y = 3
z = 2 + 3
## Method 1
print("Sum of: %i + %i = %i"%(x,y,z))
## Method 2
print("Sum of: {} + {} = {}".format(x,y,z))
## Method 3
print(f"Sum of: {x} + {y} = {z}")
Output for 1st 2 Methods:
Sum of: 2 + 3 = 5
Sum of: 2 + 3 = 5
For Method 3:
I'm getting invalid syntax
@james am I missing something in method 3?