Home > Software engineering >  How to iterate through a list and get all items stored in a variable in a specific format
How to iterate through a list and get all items stored in a variable in a specific format

Time:08-02

My program is supposed to take input for a list 'reg':

reg = []
while True:
    c = input('Enter applicable regs: ')
    if c == '':
        break
    reg.append(c.upper())

List reg would be like ['USPR', 'OSFI', 'EMIR', ...]

Now I'd want to iterate through each of the items, and store them in a variable so that the variable x looks like below:

x = '[USPR,OSFI,EMIR]' 

given there are 3 inputs from the user.

How to accomplish this?

CodePudding user response:

Use join() to concatenate list elements with a delimiter. Then concatenate the brackets around it.

x = '['   ','.join(reg)   ']'
  • Related