我使用 f-strings 而不是 print改进了我的第一个 Python 程序:
....
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'))
该程序通过 json 文件获取数据以构建科学引文:
# sample output: J A. Anderson (2018). Looking at the DNA structure, Nature. PubMed: 3256988
它工作得很好,除了(再次)我不知道如何在键没有值时从 return 语句中隐藏键值(即,json 文件中没有针对一个特定引用的这样的键)。
例如,一些科学引文没有“Pubmed”键/值 (pmd)。我不想用空白值打印“Pubmed:”,而是想摆脱它们:
# 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:
使用 publi 函数中的print语句,我可以编写以下内容:
# Pubmed: ' if len(pbm)!=0 else "", pbm if len(pbm)!=0 else ""
有谁知道如何使用f-string获得相同的结果?
谢谢你的帮助。
PS:作为一个 python 初学者,我无法解决这个特定问题,只是阅读文章Using f-string with format based on a condition