我有一个元组-
('name@mail.com',)
.
我想打开它以获得"name@mail.com"。
我该怎么做?
我是Python的新手,所以请原谅。
解包的完整语法使用元组文本的语法,以便您可以使用
tu = ('name@mail.com',)
(var,) = tu
允许使用以下简化语法
var, = tu
获取iterable
对象(如tuple
、list
等(的第一个元素和最后一个元素的最漂亮方法是使用与*
运算符不同的*
功能。
my_tup = ('a', 'b', 'c',)
# Last element
*other_els, last_el = my_tup
# First element
first_el, *other_els = my_tup
# You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:]
# Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *.
# This will result in no exceptions if you have only 1 element in the tuple.
my_tup = ('a',)
# This still works
# Last element
*other_els, last_el = my_tup
# First element
first_el, *other_els = my_tup
# other_els is [] here
tu = ('name@mail.com',)
str = tu[0]
print(str) #will return 'name@mail.com'
元组是一种序列类型,这意味着可以通过其索引访问元素。
元组就像一个列表,但是静态的,所以只需执行以下操作:
('name@mail.com',)[0]