Manage None values in F String

72 views Asked by At

I am creating a string using f string and need to avoid fields which are None.

I am currently using below code

def output(self) -> str:
        data = ''
        data += 'Books: [\n'
        for bookid, firstname, lastname in zip(self.book_id, self.first_name, self.last_name):
            data += f'{{book_id: "{bookid}", first_name: "{firstname}",last_name : "{lastname}"}},\n'
        data = data [:-2] + '\n'
        data += ']\n'
        return data

I get below output:

Books: [ { book_id: "123", first_name: "John", last_name: "None" }, { book_id: "567", first_name: "Merry", last_name: "Jones" } ]

How to ensure that None fields should not be part of the string in the for loop. I want the output as below:

Books: [ { book_id: "123", first_name: "John"}, { book_id: "567", first_name: "Merry", last_name: "Jones"} ]

2

There are 2 answers

0
VN- On BEST ANSWER

Using below I am able to get the desired output:

def output(self) -> str:
        data = ''
        data += 'Books: [\n'
        for bookid, firstname, lastname in zip(self.book_id, self.first_name, self.last_name):
          data += '{'
          data += f'book_id: "{bookid}",'
          data += f'firstname: "{firstname}",'
          if last_name:
            data += f'lastname: "{lastname}"'
         data += '}'
        data = data [:-2] + '\n'
        data += ']\n'
        return data
2
Talha Tayyab On

One way is to get the Books and omit those values which are None.

Books = [ { book_id: "123", first_name: "John", last_name: "None" } ]

You can have any number of elements in Books list.

new_Books = [{k:v for k,v in Books[x].items() if v != 'None'} for x in range(len(Books))]

if it is not a string then:

new_Books = [{k:v for k,v in Books[x].items() if v is not None} for x in range(len(Books))]

Another way can be to use if condition in the for loop but, I am exactly not sure how to implement it since do not have the actual data.