2

I have improved my first Python program using f-strings instead of print:

....
js = json.loads(data)

# here is an excerpt of my code:

def publi(type):
    if type == 'ART':
        return f"{nom} ({dat}). {tit}. {jou}. Pubmed: {pbm}"

print("Journal articles:")
for art in js['response']['docs']:
   stuff = art['docType_s']
   if not stuff == 'ART': continue
   tit = art['title_s'][0]
   nom = art['authFullName_s'][0]
   jou = art['journalTitle_s']
   dat = art['producedDateY_i']
   try:
       pbm = art['pubmedId_s']
   except (KeyError, NameError):
       pbm = ""
   print(publi('ART'))

This program fetches data through json files to build scientific citations:

# sample output: J A. Anderson (2018). Looking at the DNA structure, Nature. PubMed: 3256988

It works well, except that (again) I don't know how to hide key values from the return statement when keys have no value (ie. there is no such key in the json file for one specific citation).

For example, some of the scientific citations have no "Pubmed" key/value (pmd). Instead of printing "Pubmed: " with a blank value, I would like to get rid of both of them:

# Desired output (when pbm key is missing from the JSON file):
# J A. Anderson (2018) Looking at the DNA structure, Nature
# NOT: J A. Anderson (2018) Looking at the DNA structure, Nature. Pubmed: 

Using the print statement in the publi function, I could write the following:

# Pubmed: ' if len(pbm)!=0 else "", pbm if len(pbm)!=0 else ""

Does anyone know how to get the same result using f-string?

Thanks for your help.

PS: As a python beginner, I would not have been able to solve this specific problem just reading the post Using f-string with format depending on a condition

Laurent J
  • 25
  • 6
  • You may want to consider explicitly passing your data to the output function instead of relying on global variables. This kind of code is very hard to maintain. – MisterMiyagi Oct 10 '18 at 09:01
  • Possible duplicate of [Using f-string with format depending on a condition](https://stackoverflow.com/questions/51885913/using-f-string-with-format-depending-on-a-condition) – MisterMiyagi Oct 10 '18 at 09:02
  • @MisterMiyagi Thanks. As a python beginner, I would not have been able to solve this specific problem just reading the post [Using f-string with format depending on a condition](https://stackoverflow.com/questions/51885913/using-f-string-with-format-depending-on-a-condition) – Laurent J Oct 10 '18 at 11:17

2 Answers2

2

You can use a conditional expression in an f-string as well:

return f"{nom} {'(%s)' % dat if dat else ''}. {tit}. {jou}. {'Pubmed: ' + pbm if pbm else ''}"

or you can simply use the and operator:

return f"{nom} {dat and '(%s)' % dat}. {tit}. {jou}. {pbm and 'Pubmed: ' + pbm}"
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Thanks a lot. What if you want to do the same with the 'dat' key (= date)? For example, if 'dat' value is missing in the json file, I don't want to print the parentheses () – Laurent J Oct 10 '18 at 09:40
0

An easy but slightly fugly workaround is to have the formatting decorations in the string.

try:
    pbm = ". Pubmed: " + art['pubmedId_s']
except (KeyError, NameError):
    pbm = ""
...
print(f"{nom} ({dat}). {tit}. {jou}{pbm}")
tripleee
  • 175,061
  • 34
  • 275
  • 318