-1
string1 = "content"
string2 = "some other content"
string3 = "etc."

final_string = ""
for i in range(1, x):
  final_string += string[i]

You get the gist.. Is this possible? Converting string to a string itselves, appending a number (as a string) wouldn't work as "stringx" would be a string, thus being added to final_string as a string: final_string = content

Either way, am interested to hear any ideas - sure the "problem" can be solved in many ways, but was interested if this method is possible.

DoakCode
  • 35
  • 7
  • 2
    If you are naming variable with names like `string1`, `string2`, then you should be using a list and retrieving them with `string[1]`, etc. Then this problem goes away. – Mark Apr 12 '20 at 22:07
  • "sure the "problem" can be solved in many ways, but was interested if this method is possible.": as stated above I know it's possible to solve, though I wanted to know if it's doable the way I'm referencing. Anyhow, thanks for your input! – DoakCode Apr 12 '20 at 22:08
  • It's possible, but it involves using `eval` to execute dynamically generated code. There's no *reason* to do that, though. – chepner Apr 12 '20 at 22:09
  • 2
    `exec` is a rusty chainsaw with spikes all over the handle. Sure, if you use it very carefully, you can get the job done without hurting yourself, but it'd be a much better idea to pick a different tool. – user2357112 Apr 12 '20 at 22:21

2 Answers2

2

You can use exec for that:

string1 = "content"
string2 = "some other content"
string3 = "etc."

final_string = ""
for i in range(0, 6):
  exec("final_string += string"+str(i))

but I would suggest you put the strings into a list as suggested in one of the answer.

Riyad
  • 36
  • 1
  • `exec` is overkill; you only need `eval` to evaluate `"string" + str(i)`. – chepner Apr 12 '20 at 22:11
  • Agree. The point is that this will necessarily involve dynamically generated code, which should be avoided whenever possible. – Riyad Apr 12 '20 at 22:13
  • You don't *need* `eval` or `exec` here. You can access `globals()` – Mark Apr 12 '20 at 22:13
  • Thanks for this contribution! Exactly what I was looking for. To sum things up: eval, exec or globals can be used with the same syntax mentioned above :) – DoakCode Apr 12 '20 at 22:22
  • @MarkMeyer Assuming `string1` et al. are in the global scope, sure. – chepner Apr 12 '20 at 22:25
  • @DoakCode please make sure to investigate [Why using 'eval' is a bad practice](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Mark Apr 12 '20 at 22:29
1

I will suggest using a dictionary, ex:

my_strings = {'string1': "content", 'string3': "some other content", 'string2': "etc."}
final_string = "".join(my_strings[f'string{i}'] for i in range(1, len(my_strings) + 1))
kederrac
  • 16,819
  • 6
  • 32
  • 55