Python解包符号 * (Python unpacking operator (*))

文章解释了如何在Python中使用星号解包操作(*),如`s=*abcde`,它将字符串拆分为列表。星号用于表示接收所有未明确分配给其他变量的元素。在`s,*b,c=[1,2,3,4,5]`的例子中,*b接收剩余的元素。在你提供的例子`*s=abcde`中,需要逗号形成一个单值元组来正确执行解包。
摘要由CSDN通过智能技术生成

Answer a question

I was researching about python codegolf and saw someone use the unpacking operator in a strange way:

*s,='abcde'

I know that the unpacking operator basically iterates over a sequence. So I know that

s=['abcde']

will "unpack" the abcde string and save ['a', 'b', 'c', 'd', 'e'] in variable s.

Can someone explain as thoroughly as possible how does the

*s,='abcde'

statement work? I know it does the same thing as s=[*'abcde'] but it accomplishes it in a different way. Why is the unpacking iterator on the variable, instead of the string? Why is there a comma right after the variable name?

Answers

This is Iterable Unpacking. You may have seen it in other places to assign values to multiple variables from a single expression

a, b, c = [1, 2, 3]

This syntax includes a * to indicate that this variable should be a list containing the elements from the iterable that weren't explicitly assigned to another variable.

a, *b, c = [1, 2, 3, 4, 5]
print(b)
# [2, 3, 4]

So, what's going on in your example? There's only a single variable name being assigned to, so it's going to take all the items not assigned to another variable, which in this case is all of them. If you try just

*s='abcde'

you'll get

SyntaxError: starred assignment target must be in a list or tuple

Which is why that comma is there, as a trailing comma is how you indicate a single-value tuple.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值