简体   繁体   中英

insert 'or ' before last word in string

I'm trying to insert 'or ' before the last word in my string.

what I want it to look like:

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

what I tried to do and what I'm getting:

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

my code:

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()

How about this way:

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

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

list_as_string(a)

Out:

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

for k,v in options.items():
    v.insert(2, "or")

print(options)

options2 = {
    'o1': ['1', '2', '3'],
    'o2': ['one', 'two', 'three'],
    'o3': ['uno', 'dos', 'tres']
}

for k,v in options2.items():
    v[-1] = "or " + v[-1]

print(options2)

Not really sure which one you'd like so wrote them both, first one adds "or" as an item, second one adds the "or" string to the last item.

Other way by python string 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()

OUT:

1, 2 or 3?
one, two or three?
uno, dos or tres?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM