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
#2
class Myclass:
 
 
    def print(self):
        self.arr={'a1':'v1','a2':'v2'}
        self.key1='a1'
 
        value1=f"{self.arr[self.key1]}"
        
        print(f"{value1}")                # f-string not needed here, added for consistancy
 
        print(f"{self.arr['a1']}")

        print(f"{self.arr[self.key1]}")
 
Myclass().print()
Reply
#3
Indeed Larz60+, that is also what I would do. But it is not what Jfc is asking. According to what he shows he knows how to use f-strings. I don't know why one would scorn the blessings of f-string, but there may be reasons.

The manual of str.format shows this syntax description:
Output:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}" field_name ::= arg_name ("." attribute_name | "[" element_index "]")* arg_name ::= [identifier | digit+] attribute_name ::= identifier element_index ::= digit+ | index_string index_string ::= <any source character except "]"> + conversion ::= "r" | "s" | "a" format_spec ::= <described in the next section>
So a format string of "{arg_name[index_string]}" is allowed. I don't like this practice because the principle is to have placeholders in the format string and the values in the parameters of the "format()" method. Now external variables appear to be used in the format string as if it were an f-string. But it works:
print("{self.arr[a1]}".format(self=self))
... appears to be valid. But note: usually referencing an item would require the (string) key needing to be quoted like this: self.arr['a1']. But now these quotes must not be present and that is the reason why we cannot replace the key with a variable, like in the third example.
The only way I can think of to get around this is an ugly method: construct the format string like this.
print(("{self.arr[" + self.key1 + "]}").format(self=self))
Other (perhaps useful) possibilities I came across were the use of str.format_map() and expanding the dictionary with the "**" operator.
class Myclass:
    def print(self):
        self.arr = {'a1': 'v1', 'a2': 'v2'}
        self.key1 = 'a1'

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

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

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

        print("d: {a1}".format_map(self.arr))

        print("e: {a1}".format(**self.arr))  #which is the same as using format_map

Myclass().print()
Output:
a: v1 b: v1 c: v1 d: v1 e: v1
@jfc, does this answer your question? Why do you persist on using "format"? At the point in the program where you need to format your text you have all variables available. So you have a choice of ways to reach your goal.
Reply


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