首页 > 解决方案 > 有没有办法忽略连接字符串中的被调用变量?

问题描述

我正在编写将电子邮件起草给 1 到 4 个收件人的代码。收件人是从 Excel 工作簿中提取的。因此,如果只有 3 个收件人,则 Person4 的单元格将为空白。问题是,每次有不同数量的收件人时,为单独的电子邮件编写代码似乎不是很 Pythonic。我想为一封电子邮件编写一段代码,如果它是 None 则忽略一个被调用的变量

# collect recipent names from workbook
Person1 = sheet['BG1'].value
Person2 = sheet['BH1'].value
Person3 = sheet['BI1'].value
Person4 = sheet['BJ1'].value

# draft email
if Person4 != None:
     print('Dear ' + Person1 + ', ' + Person2 + ', ' + Person3 + ', and ' + Person4 + ',\n' + 
     'The faculty members of ... *continued body of email*')

elif Person3 != None:
     print('Dear ' + Person1 + ', ' + Person2 + ', and ' + Person3 + ',\n' + 
     'The faculty members of ... *continued body of email*')

elif Person2 != None:
     print('Dear ' + Person1 + ', and ' + Person2 + ',\n' + 
     'The faculty members of ... *continued body of email*')

else:
     print('Dear ' + Person1 + ',\n' + 
     'The faculty members of ... *continued body of email*')

有没有更聪明的方法来写这个?对于任意数量的收件人,只有一个代码块?

标签: pythonstring

解决方案


将您的姓名视为一个数组:

names = ', '.join(people[:-1]) + ' and ' + people[-1] if len(people) > 1 else people[0]
print(f'Dear {names},\n')

要填充people数组,您可以执行

people = [person for person in (Person1, Person2, Person3, Person4) if person]

可能还有一种方法可以直接使用 Excel 工作表范围执行此操作,而无需先将人员姓名分配给各个变量。


推荐阅读