python - 在句子中正确使用a或an

标签 python python-3.x

想象一个掷骰子,您想在其中打印具有良好语法的结果。

  • 'You rolled a 18' 是错误语法的一个例子。
  • 'You rolled an 18' 是良好语法的示例。
  • 'You rolled an 5' 是错误的语法。

我可以定义一个函数来执行一堆 if 语句,但这看起来不像 Pythonic。

#ideally something like this 
print(f'You rolled {a-or-an} {someint}')

最佳答案

基于discussioncomments ,我认为以下内容适合您:

def getDiceRollString(someint):
    a_or_an = "an" if someint in (11, 18) or str(someint)[0] == '8' else "a"
    return "You rolled %s %d" % (a_or_an, someint)

你可以试试看:

for i in [1, 5, 8, 11, 15, 18, 28, 81, 88, 800]:
    print(getDiceRollString(i))
#You rolled a 1
#You rolled a 5
#You rolled an 8
#You rolled an 11
#You rolled a 15
#You rolled an 18
#You rolled a 28
#You rolled an 81
#You rolled an 88
#You rolled an 800

关于python - 在句子中正确使用a或an,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56191585/

相关文章:

python - 通过删除第一个元素来修改列表

python - 将 Pandas 数据框列建模为类别列表

python - travis-ci 上的 scipy ImportError

python - 在jetson xavier nx上安装python2的llvmlite和numba库

python-3.x - 如何使用对象的内部引用克隆/深度复制 Python 3.x 字典

python-3.x - 创建 pip 包时,如何使用 Manifest.in 排除目录?

python - 凯拉斯/ tensorflow : Combined Loss function for single output

python - 根据列中的值删除行中的值,然后在 Pandas 中将单元格拆分为多行

python-3.x - 从同级目录导入 - Python 3.7

python - 在 Mac 10.14 上使用 pip 安装 python-igraph 失败并显示 "library not found for -lstdc++"