有条件地格式化字符串

时间:2015-11-27 14:06:47

标签: python string format

考虑以下代码

', '.join(['{} <{}> ({})'.format(user.nickname, user.email, user.employee_id)
                     for user in referrers])

现在,当employee_id不存在时,我想跳过()并清空空格。

referrer_strs = []
for user in referrers:
    if user.employee_id is None:
        referrer_strs.append('{} <{}>'.format(user.nickname, user.email))
    else:
        referrer_strs.append('{} <{}> ({})'.format(user.nickname, user.email, user.employee_id))

return ', '.join(referrer_strs)

我可以将它转换为理解,但有更多的pythonic方式吗?

2 个答案:

答案 0 :(得分:0)

现在代码更有趣= P

如果你想只用一行做所有事情,你可以使用“伪三元运算符”

class User:
    def __init__(self, nickname, email, employee_id=None):
        self.nickname = nickname
        self.email = email
        self.employee_id = employee_id

referrers = [
    User('macabeus', 'macabeus@gmail.com', 1),
    User('joão', 'joao@gmail.com'),
    User('josé', 'jose@gmail.com', 3)
]

print(
    ', '.join(
        ['{} <{}>{}'.format(user.nickname, user.email, ('', ' ({})'.format(user.employee_id))[user.employee_id is not None])
                     for user in referrers]
    )
)

答案 1 :(得分:0)

使用此conditional list indices removal SO post,尝试添加if逻辑:

', '.join(['{} <{}> ({})'.format(user.nickname, user.email, user.employee_id)
                     for user in referrers if not (user.employee_id is None)])