Deleting the last character in print statement when using for loop

Tags: , , , ,



I have created a list of numbers that are being inserted in a string, in this case it is a json. I am trying to delete the last character of the string after the list goes through and prints the very last element.

mylist = ['1234', '6432', '7128']
print('[')
for number in mylist:
    print(
            
                '{'
                    '"imei":' '"'+ number +'",'
                    '"url": "http://google.com/method1",'
                    '"type": "method1"'
                '},'
                '{'
                    '"imei":' '"'+ number +'",'
                    '"url": "http://google.com/method2",'
                    '"type": "event"'
                '},'
    )

print(']')

I need to remove the last character which is a comma “,” in my string, only after running through the list using the for method, so the very last element in my list will not include the “,”.

Any help would be much appreciated.

Answer

Here is a very intuitive solution which does the needed.

mylist = ['1234', '6432', '7128']
print('[')
for ind, number in enumerate(mylist):
    print(
            
                '{'
                    '"imei":' '"'+ number +'",'
                    '"url": "http://google.com/method1",'
                    '"type": "method1"'
                '},'
                '{'
                    '"imei":' '"'+ number +'",'
                    '"url": http://google.com/method2",'
                    '"type": "event"'
                '}', 
        end=''
    )
    if ind < len(mylist)-1:
        print(',')
    else:
        print('')

print(']')


Source: stackoverflow