1

我使用 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

4

2 回答 2

2

您也可以在 f 字符串中使用条件表达式:

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

或者您可以简单地使用and运算符:

return f"{nom} {dat and '(%s)' % dat}. {tit}. {jou}. {pbm and 'Pubmed: ' + pbm}"
于 2018-10-10T08:55:55.813 回答
0

一个简单但略显笨拙的解决方法是在字符串中包含格式装饰。

try:
    pbm = ". Pubmed: " + art['pubmedId_s']
except (KeyError, NameError):
    pbm = ""
...
print(f"{nom} ({dat}). {tit}. {jou}{pbm}")
于 2018-10-10T08:44:13.523 回答