-1

Here is the thing: I'm getting very long hardcoded string and I have to check the length of this string using a conditional statement and if the statement is True, I have to assign that string to variable.

So, I'm going to achieve something like:

variable = 'VERY_LONG_STRING' if len('VERY_LONG_STRING') > 1000 else "TINY_STRING"

Is it even possible?

UPDATE I have to add some explanation - as you can see there is 'VERY_LONG_STRING' two times. And I would like to ask how to use it only once?

UPDATE2 It have to be one-liner.

PS It's for testing purpose only and I have to make it for many times. My script already contain a lot of variables and I'm almost lost in them. So, I would like to avoid some unnecessary use of temporary variables.

Quanti Monati
  • 727
  • 1
  • 7
  • 26
  • 1
    remove the colon `:`? – Chris_Rands Feb 14 '19 at 11:32
  • Pretty sure the OP is asking if there's a way to do it without having to hard-code `'VERY_LONG_STRING'` twice. – Aran-Fey Feb 14 '19 at 11:33
  • There *are* ways to do this without hard-coding the string twice, for example: `variable = next((s for s in ['VERY_LONG_STRING'] if len(s) > 1000), 'TINY_STRING')`. So yeah, don't do that. Why are you trying to avoid using another variable anyway? – Aran-Fey Feb 14 '19 at 11:35
  • @Aran-Fey It's for testing purpose only and I have to make it multiple times. My script already contain a lot of variables and I'm almost lost in them. So, I would like to avoid some unnecessary use of temporary variables. – Quanti Monati Feb 14 '19 at 11:41

2 Answers2

2

If you want to condense the amount of times you use the hardcoded string, then assign it to a variable:

LONG_STRING = 'VERY_LONG_STRING'
TINY_STRING = 'TINY_STRING'
variable = LONG_STRING if len(LONG_STRING) > 1000 else TINY_STRING
print(variable)
>> TINY_STRING
AK47
  • 7,795
  • 6
  • 33
  • 57
2
variable = "VERY_LONG_STRING"
if len(variable) < 1000:
    variable = "TINY_STRING"
VijayKillu
  • 436
  • 3
  • 8
  • @AK47 Probably not, because I need to do that in one line. As I mentioned earlier It's for testing purpose only and I have to make it multiple times. My script already contain a lot of variables and I'm almost lost in them. So, I would like to avoid some unnecessary use of temporary variables. – Quanti Monati Feb 14 '19 at 11:43
  • Why does it need to be done in one line ? It's better to write clean and understandable code than to just squash everything into one line ? this solution here is clean and readable – AK47 Feb 14 '19 at 11:59