python - 有没有办法忽略连接字符串中的被调用变量?
问题描述
我正在编写将电子邮件起草给 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*')
有没有更聪明的方法来写这个?对于任意数量的收件人,只有一个代码块?
解决方案
将您的姓名视为一个数组:
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 工作表范围执行此操作,而无需先将人员姓名分配给各个变量。
推荐阅读
- python - 如何在远程 shell 的上下文中进行 pdb 的 stdin/stdout 重定向?
- javascript - 有没有办法在 Nuxt 中为缩小的 JS 脚本标签添加属性?
- javascript - 无限循环页面
- reactjs - 如何触发深度嵌套子组件的刷新
- java - 为什么 com.fasterxml.jackson.core.type.TypeReference 实现 Comparable 接口?
- python - 如何使它只有某些人才能发消息?
- mongodb - 在多个字段聚合中排序
- capl - CAPL:动态改变对ECU的CAN ID请求
- c - C语言中的异或运算
- java - 如何管理 Spring Boot 项目之间的共享代码?