Python 插入';或';在字符串的最后一个单词之前
我试图在字符串的最后一个单词前插入'or' 我希望它看起来像什么:Python 插入';或';在字符串的最后一个单词之前,python,Python,我试图在字符串的最后一个单词前插入'or' 我希望它看起来像什么: >>>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
>>>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)
输出:
python字符串api的其他方式:
def main():
options = {
'o1': ['1', '2', '3'],
'o2': ['one', 'two', 'three'],
'o3': ['uno', 'dos', 'tres']
}
for _ in options.keys():
i = list((', '.join(options[_]) + '?').rpartition(","))
i[1] = " or"
j = ''.join(i)
print(j)
main()
输出:
谢谢,但不是我想要的。如果我做了其中一个,那么无论何时输入3/3/tres,它都是错误的,因为它将是或3/3/or tres。我只需要编辑选项字符串,而不是dict项。
'2, one, or tres'
def main():
options = {
'o1': ['1', '2', '3'],
'o2': ['one', 'two', 'three'],
'o3': ['uno', 'dos', 'tres']
}
for _ in options.keys():
i = list((', '.join(options[_]) + '?').rpartition(","))
i[1] = " or"
j = ''.join(i)
print(j)
main()
1, 2 or 3?
one, two or three?
uno, dos or tres?