Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 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', '[email protected]', '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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...