Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
string format challenge
#1
My goal is to use the format function to print one value of a dict based on a key known at runtime.
I can do it with the an f-string (first print)
I can do it with a fixed key and the format function (second print)
but I can not do it with a dynamic key and the format function (error)
Is it possible to do this by only modifying the "{self.arr[self.key1]}" part of the third print ?
#!/usr/bin/python3

class Myclass:


   def print(self):
     self.arr={'a1':'v1','a2':'v2'}
     self.key1='a1'

     value1=f"{self.arr[self.key1]}"
     print(value1)

     print("{self.arr[a1]}".format(self=self))

     print("{self.arr[self.key1]}".format(self=self))

Myclass().print()
Output:
Output:
v1 v1
Error:
Traceback (most recent call last): File "./ch25-.py", line 17, in <module> Myclass().print() File "./ch25-.py", line 15, in print print("{self.arr[self.key1]}".format(self=self)) KeyError: 'self.key1'
Reply


Messages In This Thread
string format challenge - by jfc - Oct-21-2021, 09:28 AM
RE: string format challenge - by Larz60+ - Oct-21-2021, 09:45 AM
RE: string format challenge - by ibreeden - Oct-23-2021, 10:30 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  PySpark Coding Challenge cpatte7372 4 6,149 Jun-25-2023, 12:56 PM
Last Post: prajwal_0078
  Set string in custom format korenron 4 1,130 Jan-16-2023, 07:46 PM
Last Post: mutantGOD
  Format String NewPi 2 993 Oct-10-2022, 05:50 PM
Last Post: NewPi
  TypeError: not enough arguments for format string MaartenRo 6 2,974 Jan-09-2022, 06:46 PM
Last Post: ibreeden
  Print first day of the week as string in date format MyerzzD 2 2,057 Sep-29-2021, 06:43 AM
Last Post: MyerzzD
  string.format() suddenly causing errors with google drive API zwitrader 0 1,784 Jun-28-2021, 11:38 PM
Last Post: zwitrader
  String to Date format SAF 2 2,487 Apr-06-2021, 02:09 PM
Last Post: snippsat
  MySQLdb._exceptions.ProgrammingError: not enough arguments for format string. farah97 0 3,369 Jan-22-2020, 03:49 AM
Last Post: farah97
  Highlight/Underline a string | ValueError: zero length field name in format searching1 1 3,046 Jul-01-2019, 03:06 AM
Last Post: metulburr
  write image into string format into text file venkat18 2 4,449 Jun-01-2019, 06:46 AM
Last Post: venkat18

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020