Reputation: 21
Is there a single line command to add two strings contained in a tuple to two existing strings in a program?
This is essentially what I want to do but in a shorter way,
t=("hi","hello")
x="test"
y="python"
x+=t[0]
y+=t[1]
I was thinking maybe there is a code like this that actually works,
x+,y+=t
Using python's in place addition with unpacked tuples - I really liked the complex number solution given in this similar question, but I cannot use it since my values are strings. Or is there a way I can manipulate my data (without going into too many lines of code) so that this method can be used?
Upvotes: 0
Views: 296
Reputation: 310
A single line of code doing what you expect is given below,
Code:
x, y = ["".join(i) for i in zip([x,y], t)]
Here zip() makes an iterator which aggregates the elements from each of the sequences passed to it. In this case it would be [(x, t[0]), (y, t[1])]
. .join() concatenates the elements of the list passed to it with a separator (""
in this case).
Upvotes: 1
Reputation: 677
Using this answer from the question you linked, you can do this:
from operator import add
t = ("hi", "hello")
x = "test"
y = "python"
x, y = map(add, (x, y), t)
Honestly, it is rather hard to read and I would advise against using it. As far as default Python syntax goes, I doubt there is anything you could use.
Upvotes: 2