找到将字符串添加到元组的方法

0 投票
2 回答
2363 浏览
提问于 2025-04-16 22:12
y="Peter Email: peter@rp.com Phone: 91291212"
z="Alan Email: alan@rp.com Phone: 98884444"
w="John Email: john@rp.com Phone: 93335555"
add_book=str(y) ,"" + str(z) ,"" + str(w)

**我想把一个联系人添加到我的通讯录里,但我不太确定怎么把字符串“details”加到add_book里面。我还发现因为它是一个元组,所以我不能用append方法。

details = raw_input("Enter name in the following format: name Email: Phone:")                      
        print "New contact added"
        print details 
if details in add_book:
    o=add_book+details
    print "contact found"
    print details
print add_book

address_book = {}
address_book['Alan'] = ['alan@rp.com, 91234567']#this is what I was supposed to do:

#but when I print it out, the output I get is:

{'Alan': ['alan@rp.com, 91234567']} #but I want to remove the '' and {}

我在用Python编程方面还是个新手,所以我真的需要尽可能多的帮助,谢谢:)!!

2 个回答

2

一个简单的解决办法是用列表来代替元组。你可以通过把add_book的初始化从:

add_book=str(y) ,"" + str(z) ,"" + str(w)

改成:

add_book = [y,z,w]
#No need to call str() every time because your data are already strings

不过,把数据组织成字典的列表不是更合理吗?比如说:

contacts = ["Peter", "Alan", "John"]
addr_book = [len(contacts)]

for i in range(len(contacts)):
    contact = contacts[i]
    email= raw_input(contact+"'s email: ")
    phone= raw_input(contact+"'s phone: ")

    addr_book[i] = {'name':contact, 'email':email, 'phone':phone}

另外:
如果我理解你的问题没错,你对程序输出的格式有具体的要求。如果你使用上面的数据格式,你可以创建任何你想要的输出。例如,这段代码

def printContact(contact):
    print contact['name']+': ['+contact[email]+','+contact[phone]+']'

会输出类似这样的内容:

Alan: [alan@email.com,555-555-5555]

当然,你可以随意修改它。

2

首先,[] 是一个列表,而元组是 (,);

所以你想要的是

address_book['Alan'] = ('alan@rp.com', '91234567')

但这看起来有点奇怪。我会创建一个类

class Contact(object):
    name = "Contact Name"
    email = "Contact Email"
    ph_number = "00000000"

    def __str__(self):
        return "%S: %s, %s" % (self.name, self.email, self.ph_number)

然后

address_book = []
contact_alan = Contact()
contact_alan.name = "Alan"
contact_alan.email = "alan@rp.com"
contact_alan.ph_number = "91234567"

print contact

(我现在不在有 Python 的机器旁边,所以可能会有些错误。等我能到机器旁边时会测试一下。)

编辑:正如 Paul 在他的评论中指出的:

class Contact(object):

    def __init__(self, name, email, ph_number):
        self.name = name
        self.email = email
        self.ph_number = ph_number

contact_alan = Contact(name="Alan", email = "alan@rp.com", ph_number="91234567")

撰写回答