拆分字符串并解压缩为变量的 Pythonic 方法? [英] Pythonic way to split a string and unpack into variables?
本文介绍了拆分字符串并解压缩为变量的 Pythonic 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简单问题:给定一个字符串
Simple question: given a string
string = "Word1 Word2 Word3 ... WordN"
有没有pythonic的方法来做到这一点?
is there a pythonic way to do this?
firstWord = string.split(" ")[0]
otherWords = string.split(" ")[1:]
比如开箱什么的?
谢谢
推荐答案
自 Python 3 和 PEP 3132,你可以使用扩展解包.
Since Python 3 and PEP 3132, you can use extended unpacking.
通过这种方式,您可以解压缩包含任意数量单词的任意字符串.第一个将存储到变量 first
中,其他的将属于列表(可能为空)others
.
This way, you can unpack arbitrary string containing any number of words. The first will be stored into the variable first
, and the others will belong to the list (possibly empty) others
.
first, *others = string.split()
另外,注意 .split()
的默认分隔符是一个空格,所以你不需要明确指定它.
Also, note that default delimiter for .split()
is a space, so you do not need to specify it explicitly.
这篇关于拆分字符串并解压缩为变量的 Pythonic 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文