Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

iterable unpacking - Invalid syntax python starred expressions

I am trying to unpack set of phone numbers from a sequence, python shell in turn throws an invalid syntax error. I am using python 2.7.1. Here is the snippet

 >>> record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
 >>> name, email, *phone-numbers = record
 SyntaxError: invalid syntax
 >>>

Please explain. Is there any other way of doing the same?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are using Python 3 specific syntax in Python 2.

The * syntax for extended iterable unpacking in assignments is not available in Python 2.

See Python 3.0, new syntax and PEP 3132.

Use a function with * splat argument unpacking to simulate the same behaviour in Python 2:

def unpack_three(arg1, arg2, *rest):
    return arg1, arg2, rest

name, email, phone_numbers = unpack_three(*user_record)

or use list slicing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...