如何将新行字符插入列表列表中

时间:2016-02-14 02:46:36

标签: python python-2.7

我试图在邮件标签的名称和地址部分之间插入换行符。因为它是一个列表列表,所以不允许我在mailingLabelList的各个部分之间输入\ n。

def main():
    """ Open's file, reads customer information into a list, closes the file"""
    custFile = open('customerData.txt','r')
    mailingLabelFile = open('mailingLabels.txt','w')
    customerList = generateList(custFile)
    mailingLabelList = generateMailingLabel(customerList)
    mailingLabelFile.write("mailingLabels")
    mailingLabelFile.close()
    mailingLabelFile = open('mailingLabels.txt','r')

    # Echo first and last enter from the customerList
    print "customerList[0]:", customerList[0]
    print "customerList[-1]:",customerList[-1]

    print mailingLabelList[0]

    custFile.close()
    mailingLabelFile.close()

def generateList(custFile):
    """ Reads customer data from file and returns a list of customers"""
    customers = []
    for line in custFile:
        # Strip the new-line character from the end of the line, then split
        # the line on the commas (',') to get a list of customer fields
        custInfoList = line.strip().split(',')
        customers.append(custInfoList)
    return customers

def generateMailingLabel(customerList):
    """Reads customer data from custoemrList and sorts out the female customers in Iowa
    and creates a mailing label for those customers"""
    mailingLabelList = []
    for list in customerList:
        if list[5] == 'IA' and list[10] == 'female':
            mailingLabelList.append(list[0] + ' ' + list[2] + ' ' + list[3] + ' ' + list[4] + ' ' + list[5] + ' ' + list[6])
        return mailingLabelList

main()

1 个答案:

答案 0 :(得分:0)

def generateMailingLabel(customerList):
    """Reads customer data from custoemrList and sorts out the female customers in Iowa
    and creates a mailing label for those customers"""
    mailingLabelList = []
    for list in customerList:
        if list[5] == 'IA' and list[10] == 'female':
            thing_to_append = ''.join(str(s) for s in list) + "\n"
            mailingLabelList.append(thing_to_append)
        return mailingLabelList