【问题标题】:Deleting the last character in print statement when using for loop使用for循环时删除打印语句中的最后一个字符
【发布时间】:2021-02-08 12:31:52
【问题描述】:

我创建了一个插入字符串的数字列表,在本例中它是一个 json。我试图在列表通过并打印最后一个元素后删除字符串的最后一个字符。

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

我需要删除字符串中的最后一个字符,即逗号“,”,只有在使用 for 方法遍历列表之后,所以列表中的最后一个元素将不包含“,”。

任何帮助将不胜感激。

【问题讨论】:

标签: python json list for-loop replace


【解决方案1】:

解决方案:
这应该可以解决您的问题:

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

print(']')

输出:

[
{"imei":"1234","url": "http://google.com/method1","type": "method1"},{"imei":"1234","url": http://google.com/method2","type": "event"},
{"imei":"6432","url": "http://google.com/method1","type": "method1"},{"imei":"6432","url": http://google.com/method2","type": "event"},
{"imei":"7128","url": "http://google.com/method1","type": "method1"},{"imei":"7128","url": http://google.com/method2","type": "event"}
]

【讨论】:

  • 请在此答案中提及拒绝投票的原因?
【解决方案2】:

这是一个非常直观的解决方案,可以满足您的需要。

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

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多