0

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?

Hiya
  • 21
  • 3
  • 1
    strings are immuteable - the old one gets replaced with newly created ones. what you got above is fine - using imports and other "magic" to make it fancier is deterimental to easy understanding what the code does: **"Simple is better than complex."** - see [Zen of Python (pep-0020)/](https://www.python.org/dev/peps/pep-0020/) – Patrick Artner May 27 '20 at 09:19
  • @PatrickArtner i know :( but i only want to make it compact, no one will be reading the code but me. Thanks for the link! – Hiya May 27 '20 at 15:58

2 Answers2

2

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.

Luka Mesaric
  • 657
  • 6
  • 9
1

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).

satilog
  • 310
  • 2
  • 11