在Python中删除列表中的特定字符

时间:2015-04-13 14:06:35

标签: python dictionary

我有一个列表,里面有几个dicts,它们都用逗号“,”分隔。发生的事情是,当我创建这个列表时,我在for循环中添加一个逗号,在每个dict之后将它们分开,但它也在最后一个字典之后添加最后一个逗号。类似的东西:

"guests": [{
    "age": "18",
    "birthDate": null,
    "emailAddress": null,...
    ....
    "name": {
    "prefix": "Mr.",
    "firstName": "James",
    "middleName": "",
    "lastName": "Jones",
    "suffix": ""
    }
},----------------------------->This comma
]

我认为最后一个逗号在尝试向Web服务发出请求时会产生一些问题。那么,我怎样才能删除列表中最后一个逗号?

由于

修改

列表的创建发生在for循环中。类似的东西:

participants_body = ''

for guest in guests_info:

        post_body = '{"profile": {"name": {"title": "' + guest["title"] + '","firstName": "' \
                           + guest["first_name"] + '","lastName": "' + guest["last_name"] \
                           + '"},"age": 18},"preferences": {"avatarIdentifier": "15655408","favoriteCharacterIdentifier":' \
                             ' "15655408"},"friendsAndFamily": {"groupClassification": {"name": "TRAVELLING_PARTY"},' \
                             '"accessClassification": {"name": "PLAN_VIEW_SHARED"}}}'

        response = requests.post(url, data=post_body, headers=headers)

        json_response = response.json()

       participants_body = '{"age": "' + str(json_response["profile"]["age"]) + '","birthDate": null,"emailAddress": null,' \
                            '"phone": null,"primary": false,"swid": null,"guid": "' + guid + '","gender": null,"type": null,' \
                            '"participantId": "' + p_id + '","profileLink": "https://env5.nge.api.go.com' + profileLink + '", ' \
                            '"infantSittingWithAdult": false,"avatar": null,"itemsAssigned": ' \
                            '["' + item_id + '"],"address": null,"phoneNumber": null,"dataType": "basic",' \
                            '"isRoomAssigned": true,"isVacationOfferAssigned": true,"ageGroup": "","name": {' \
                            '"prefix": "' + json_response["profile"]["name"]["title"] + '","firstName": "' \
                            + json_response["profile"]["name"]["firstName"] + '","middleName": "","lastName": "' \
                            +

                           json_response["profile"]["name"]["lastName"] + '","suffix": ""}},'------------> HERE IS THE COMA

        post_body_participants += participants_body

所以,这就是为什么我得到了昏迷。我只需要在for循环后删除它

修改

我正在创建一条Post消息,我收到了这个错误:

{u'errors': [{u'message': u'org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class com.disney.wdpro.service.booking.webservice.resource.ParticipantWithAssignmentResourceCollection] from JSON String; no single-String constructor/factory method'}]}

我读了几个SO问题,他们提到可能发生这种情况是因为json格式的错误。

此外,我可以看到帖子的主体是如何在日志中的其他消息中创建的,并且最后一个逗号不存在,所以可能发生了什么

2 个答案:

答案 0 :(得分:3)

我不确定你为什么要把它作为字符串创建。你可以更快乐地将dicts创建为dicts。代码更具可读性,可在以后更改时帮助您。除此之外,它将消除像您一样经历的小错误。

post_body = {
    'profile': {
        'name': {
            'title': guest['title'],
            'firstName': guest['first_name'],
            'lastName': guest['last_name'] },
        'age': 18 },
    'preferences': {
        'avatarIdentifier': 15655408,
        'favoriteCharacterIdentifier': 15655408 },
    'friendsAndFamily': {
        'groupClassification': {
            'name': 'TRAVELLING_PARTY' },
        'accessClassification': {
            'name': 'PLAN_VIEW_SHARED' }
    }
}

很容易将该dict转换为JSON字符串:

import json
post_body = json.dumps(post_body)

您可以通过participants_body响应创建列表来执行相同的操作。只需创建上面的一个字典,然后用post_body_participants.append(participants_body)附加它。同样,您可以使用json.dumps(post_body_participants)的JSON字符串形式访问该列表。

答案 1 :(得分:1)

如果你使用内置的json编码器/解码器来构建你的json字符串,你会省去很多痛苦。手工构建它们容易出错。为什么不站在巨人的肩膀上呢?

import requests
import json

participants =[]

for guest in guests_info:
    #Build Python objects and not json strings
    #Convert it all to json later
    post_body = {
        'profile': {
            'name': {
                'title': guest['title'],
                'firstName': guest['first_name'],
                'lastName': guest['last_name'] },
            'age': 18 },
        'preferences': {
            'avatarIdentifier': 15655408,
            'favoriteCharacterIdentifier': 15655408 },
        'friendsAndFamily': {
            'groupClassification': {
                'name': 'TRAVELLING_PARTY' },
            'accessClassification': {
                'name': 'PLAN_VIEW_SHARED' }
        }
    }

    #The requests module has json encoding/decoding built in
    response = requests.post(url, json=post_body, headers=headers)  
    #Or you could use Python's built in json module
    #response = requests.post(url, data=json.dumps(post_body), headers=headers)  

    json_response = response.json() #This decodes the json string in the response to a Python object


    participant = {
        "age": json_response["profile"]["age"],
        "birthDate": None,
        "emailAddress": None,
        "phone": None,
        "primary": False,
        "swid": None,
        "guid": guid,
        "gender": None,
        "type": None,
        "participantId": p_id,
        "profileLink": "https://env5.nge.api.go.com" + profileLink + ,
        "infantSittingWithAdult": False,
        "avatar": None,
        "itemsAssigned": [item_id],
        "address": None,
        "phoneNumber": None,
        "dataType": "basic",
        "isRoomAssigned": True,
        "isVacationOfferAssigned": True,
        "ageGroup": "",
        "name": {
            "prefix": json_response["profile"]["name"]["title"],
            "firstName": json_response["profile"]["name"]["firstName"],
            "middleName": "",
            "lastName": json_response["profile"]["name"]["lastName"],
            "suffix": ""}
        }
    }

    participants.append(participant)