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