Python:如何写这个 "pythonic way"?

标签 python

我知道这不是“不错的”python 东西:

username = u'{0}{1}{2}'.format(
    form.cleaned_data['email'].split('@', 1)[0],
    u'_at_',
    form.cleaned_data['email'].split('@', 1)[1]
)

您将如何以更 pythonic = 易于理解和优化的方式编写它?

最佳答案

由于您的意图只是替换 @ 符号,只需替换它:

username = form.cleaned_data['email'].replace('@', '_at_')

扩展一点(因为我喜欢它),如果你没有像上面那样的简单替换,你通常希望避免在同一个分隔符上多次调用 str.split .所以显而易见的第一步是先存储结果:

data = form.cleaned_data['email'].split('@', 1)
username = '{0}{1}{2}'.format(data[0], '_at_', data[1])

接下来,正如其他人已经指出的那样,您应该将常量移动到格式字符串中:

username = '{0}_at_{2}'.format(data[0], data[1])

然后,由于您只将 data 的(只有两个)元素传递给函数,您可以使用参数解包,此时您还可以再次内联数据:

username = '{0}_at_{2}'.format(*form.cleaned_data['email'].split('@', 1))

另一种解决方案适用于多次拆分的情况,即加入替换字符串:

username = '_at_'.join(stringWithMultipleAts.split('@'))

关于Python:如何写这个 "pythonic way"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33302654/

相关文章:

Python 决策树 GraphViz

python - 将空格转换为列表中的 %20

python - pandas read_csv 编码奇怪的字符

python - 如何使用 Scrapy 抓取下一页

python - python中的参数传递

python - 格式化字典打印输出

python - h5py.File(path) 无法识别文件夹路径

python - 如何将 HTML block (使用 python)插入当前工作的网站....?

Python 多处理 : Ending an infinite counter

python - 如何根据列表中的项目请求输入?