Home > Blockchain >  Can I pass all variable arguments to a .format() method?
Can I pass all variable arguments to a .format() method?

Time:06-17

x="this" 
y="is" 
z="cake" 
print("{x}{y}{z}".format(z,y,x))

The code above gives the following error:

Traceback (most recent call last):
  File "C:\Users\....\class_var_and_instance_var.py", line 36, in <module>
    print("{x}{y}{z}".format(z,y,x))
KeyError: 'x'

CodePudding user response:

Way 1 : using .format()

print("{x}-{y}-{z}".format(x=x, y=y, z=z))

Way 2: using f-strings

print(f"{x}{y}{z}")

Way 3: using format(**kwargs)

vars = dict(x="this", y="is", z="cake")
print("{x}-{y}-{z}".format(**vars))

CodePudding user response:

This one should work:

x="this" 
y="is" 
z="cake" 
print("{x}{y}{z}".format(z=z,y=y,x=x))

your code didn't work since format() expects explicit keywords

  • Related