python - 如果数字为 0 或大于 1,则将 's' 添加到字符串

标签 python python-3.x

我正在 Flask 中制作一个 Web 应用程序,我想更好地格式化帖子投票。

我希望它不要说“1 票”,而是说“1 票”等等。

我的尝试:

def format_post_votes(post):

    output = ''

    if post.votes == 0 or post.votes > 1:
        output = 's'
    else:
        output = ''

    return f'{post.votes}{output}'

有没有更有效的方法来做到这一点?...

最佳答案

您可以将其简化为:

def format_post_votes(post):
    return f'{post.votes}{"" if post.votes == 1 else "s"}'

关于python - 如果数字为 0 或大于 1,则将 's' 添加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58002545/

相关文章:

python - 更改 Python 中的日期时间格式

python - HTML 新手问题 : Colored Background for Characters in Django HttpResponse

python - 在 Python 3.X 中从 HTTP 响应中获取和评估 Python 代码

python - 在 Pycharm 和终端中运行带有参数的 python 脚本

python - 如何将包含 '/' 的值插入到 sqlite 中?

python - 为什么运行unittest时会出现 "-m"和 "unittest"?

Python 列表多重赋值

python - 根据每个 DataFrame 行的匹配值将列表的值添加到 pandas DataFrame 列

python - Protobuf 编译问题

python-3.x - 使用 Python 进行多重切片分配