简体   繁体   English

在Python中将.split()与用户输入一起使用时出错

[英]Error with useing .split() with user input in python

So I am trying to make a basic address book in python that can save contacts and load them using pickle, but for some reason I get an error when I try to put in a contact My code is: 所以我试图用python创建一个基本的地址簿,该地址簿可以保存联系人并使用pickle加载它们,但是由于某些原因,当我尝试放入联系人时出现错误。我的代码是:

import pickle
class Contact:
    def __init__(self, firstname, lastname, phonenumber, adress):
        self.firstname = firstname
        self.lastname = lastname
        self.phonenumber = phonenumber
        self.adress = adress
print('Welcome to your adress book, would you like to:\n1. Add a contact\n2. Look at a contact\n3. Close the program')
while True:
    choice = int(input())
    if choice == 1:
        print('Type in their information, with the format\nfirstname lastname phonenumber adress')
    info = input().split()
    pickle.dump(info, open(info[0].lower() + '.pkl' , 'w+'))
    continue
elif choice == 2:
    print('What is their first name?')
    fn = input().lower()
    x = pickle.load(open(fn + '.pkl', 'rb'))
    print(x[0] + x[1] + x[2] + x[3])
    continue
elif choice == 3:
    break
else:
    print('Invalid input.')
    continue

The error says: 错误提示:

Traceback (most recent call last):
  File "C:\Users\keith\Desktop\adress_book.py", line 13, in <module>
    info = input().split()
  File "<string>", line 1
    Bob Smith 123456789 123street
            ^
SyntaxError: invalid syntax

Any help would be greatly appreciated, thanks. 任何帮助将不胜感激,谢谢。

I think you're looking for raw_input . 我认为您正在寻找raw_input Unlike in Python 3, in Python 2.x, input parses and evaluates the string as a Python expression. 与Python 3不同,在Python 2.x中, input将字符串解析并评估为Python表达式。

From the input docs: input文档:

This function does not catch user errors. 此功能不会捕获用户错误。 If the input is not syntactically valid, a SyntaxError will be raised. 如果输入在语法上无效,则将引发SyntaxError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM