python - 在字符串的最后一个单词之前插入 'or '

标签 python

我试图在字符串的最后一个单词之前插入“或”。

我希望它看起来像:

>>>test, test1, test2, or test3?

我尝试做什么以及我得到了什么:

i = input(', {}'.format('or ' if options[_][-1:] else '').join(options[_]) + '?')  
>>>test, or test1, or test2, or test3?

我的代码:

def main():
    options = {
        'o1': ['1', '2', '3'],
        'o2': ['one', 'two', 'three'],
        'o3': ['uno', 'dos', 'tres']
    }

    values = []

    i = ''
    for _ in options.keys():
        while i not in options[_]:
            i = input(', '.join(options[_]) + '?')
        values.append(i)

    print(values)

main()

最佳答案

这样怎么样:

def list_as_string(data):
    return ", ".join(data[:-1]) + ", or " + data[-1]

a = ['2', 'one', 'tres']

list_as_string(a)

输出:

'2, one, or tres'

关于python - 在字符串的最后一个单词之前插入 'or ',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48959918/

相关文章:

python - 如何捕获使用 pythonw 执行的 Python 脚本的标准输出?

python - 我的 ipy.exe 在哪里?

python - matplotlib/pandas条形图的简单定制(标签、刻度等)

python - 将 PIL/PILLOW 图像复制到 Windows 剪贴板

python - fasttext 中多标签的正确标签格式是什么?

python - 如何通过在后台运行的程序读取参数?

python - 当本地主机正在工作时,我无法通过 IP 地址看到我的 Python Django 服务器

python - 类型提示与鸭子类型

python - astriod包中的Pylint无限递归

python - 如何让 request.route_url 使用 Pyramid 吐出 https 链接而不是 http?