-1

I have this string: my_str='a pi{ece} of t{ext}'

and these args: args=['ece', 'ext']

When calling: >>> my_str.format(*args)

It gives me: KeyError 'ece'

Any help?

Charming Robot
  • 2,460
  • 2
  • 17
  • 34
  • What were you expecting that to do? Why did you use named placeholders and pass positional arguments? – user2357112 Nov 30 '18 at 22:49
  • I'm forced to implement it that way. Both with *args and named placeholders – Charming Robot Nov 30 '18 at 22:50
  • 1
    Not likely. If we had more context, we might be able to tell you what you should actually do. – user2357112 Nov 30 '18 at 22:51
  • 1
    this `print( my_str.format(**dict( zip(args,args))) )` will print what you want. Have fun figuring out why. the other one is simpler: `'a pi{} of t{}.format(*args)'`. Maybe this will help: [understanding-kwargs-in-python](https://stackoverflow.com/questions/1769403/understanding-kwargs-in-python) .. or this: [unpacking-argument-lists](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists) – Patrick Artner Nov 30 '18 at 23:10
  • The formatter accesses `args['ece']`. Try this yourself in the interpreter. – torek Nov 30 '18 at 23:13

1 Answers1

0

I think what you're looking for is fstring. Fstring was added to python 3.6.

hello = "Hello"
person = "Jimmy"

args = [hello, person]
greeting = f"{args[0]}, {args[1]}"
print(greeting)

If you really want to use .format()

hello = "Hello"
person = "Jimmy"

args = [hello, person]
greeting = "{}, {}".format(*args)
print(greeting)

or

hello = "Hello"
person = "Jimmy"

args = [hello, person]
greeting = "{first}, {second}".format(first=args[0], second=args[1])
print(greeting)

Please google fstring and .format()

Fstring is generally faster

ZuperZee
  • 1
  • 2