Let's say I have a string
x = '32'
And I already have a 1 length tuple defined with something like
tuple_a = ('12',)
I want to transform the string into a 1 member tuple and add the 2 tuples together so the outcome is something like
tuple_a + x = ('12','32')
and not something like:
tuple_a + x = ('12','3','2')
Which is all I could managed to do by now.
Tuples are immutable, so you cannot modify tuple_a
to insert another element. You'd have to construct a new tuple, and assign that back to your tuple_a
variable.
>>> x = '32'
>>> tuple_a = ('12',)
>>> tuple_a = (tuple_a[0], x)
>>> tuple_a
('12', '32')
As @iCodez mentioned, the +
operator is defined for tuples, so you could take advantage of that too if you wish
>>> tuple_a = ('12',)
>>> tuple_a + (x,)
('12', '32')
How about tuple_a + (x,)
?
>>> tuple_a = ('12',)
>>> x = '32'
>>> tuple_a + (x,)
('12', '32')
You cannot modify a tuple. You will have to create a new one.
If you need to modify, better use a list.
x = '32'
list1 = ['12']
list1.append(x)
print list1 # ['12','32']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.