Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 条件格式字符串_Python_String_Format - Fatal编程技术网

Python 条件格式字符串

Python 条件格式字符串,python,string,format,Python,String,Format,考虑以下代码 ', '.join(['{} <{}> ({})'.format(user.nickname, user.email, user.employee_id) for user in referrers]) 我可以将其转换为以便于理解,但有没有更具python风格的方法呢?代码现在更有趣了=p 如果您想在一行中完成所有操作,可以使用“伪三元运算符” class User: def __init__(self, nickna

考虑以下代码

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

我可以将其转换为以便于理解,但有没有更具python风格的方法呢?

代码现在更有趣了=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]
    )
)
类用户:
def uuu init uuuu(自我、昵称、电子邮件、员工id=None):
self.昵称=昵称
self.email=电子邮件
self.employee\u id=employee\u id
推荐人=[
用户('macabeus','macabeus@gmail.com', 1),
用户('joão','joao@gmail.com'),
用户('josé','jose@gmail.com', 3)
]
印刷品(
“,”加入(
['{}{}.format(user.昵称,user.email,(''''({})'.format(user.employee_id))[user.employee_id不是None])
供推荐人中的用户使用]
)
)
使用此选项,尝试添加if逻辑:

', '.join(['{} <{}> ({})'.format(user.nickname, user.email, user.employee_id)
                     for user in referrers if not (user.employee_id is None)])
,'.join(['{}({})].format(user.昵称、user.email、user.employee\u id)
对于推荐人中的用户(如果不是(user.employee\u id为None)))

此代码看起来不错。它是可读的。不要更改它。我知道它是可读的,但我想知道是否有一些字符串格式的魔力,例如,{}{?()}让我们试试这个。也许你能找到什么。但我不这么认为。
', '.join(['{} <{}> ({})'.format(user.nickname, user.email, user.employee_id)
                     for user in referrers if not (user.employee_id is None)])