Home > Software design >  Can you insert anything other than a variable in {curly braces} of an f string literal?
Can you insert anything other than a variable in {curly braces} of an f string literal?

Time:10-10

I was writing a print statement to test code. But I realised I mistakenly had put a (self-defined) object (from a different class) in the {}.

I have already add the str method in the object to be able to call off print on it.

I tried to see if {print(thatobject)} would give me something.

When it didn't, I tried to read the document to understand what are the valid inputs for the {curly braces}. But couldn't understand it

Can someone explain what would be the valid inputs for the {curly braces} in a f string literal.

**Excuse me for using ppor terminology and just calling them "inputs". I hope you get what I mean (Variables, Function outputs, etc)

***I am aware that methods like len() can also be inserted in the {}.

class Player:
    
    def __init__(self,name):
        
        self.name = name
        self.all_cards = []
        
    def add_cards(self,new_cards):
        '''
        Will be able to add multiple cards or just a single
        '''        
        if type(new_cards) == list:
            self.all_cards.extend(new_cards)
        else: 
            self.all_cards.append(new_cards)
       
    
    def remove_one(self):
        pass
    
    def __str__(self):
        return f"Player {self.name} has {len(self.all_cards)} cards. They are {print(self.all_cards)}"

CodePudding user response:

in f-string's {curly braces} you can use any variables, class objects, executable expressions, function callings, etc. Anything can be used in brackets. You saw None on {print(self.all_cards)} because print function only returns None in python. If you want to print all_cards only remove that print method from it. Use like this {self.all_cards}. As you can read on the official docs. Everything inside the {brackets} is expressions that are evaluated at runtime and then formatted to that string. And if we elaborate your f-string working:

    return f"Player {self.name} has {len(self.all_cards)} cards. They are {print(self.all_cards)}"

it will execute {self.name} get the variable value place it in that position, len(self.all_cards) len method is being executed and return the length of the self.all_cards list, {print(self.all_cards)} it will execute print method which only returned None. And f-string will return like this after execution and formatting:

Player test has 0 cards. They are None
  • Related