0

New to Python, I have the following script:

#!/usr/bin/env python3
import sys

env = sys.argv[1:]  # The name of the environment we're executing over ('Dev', 'Test', 'Prod', etc)

print('Executing against ' + env)

Above, the script should be invoked with an env argument that is then printed out to STDOUT.

Is there any more elegant way to inject the env variable into the string being printed (so I don't have that nasty-looking + concatenation going on)?

tripleee
  • 175,061
  • 34
  • 275
  • 318
hotmeatballsoup
  • 385
  • 6
  • 58
  • 136
  • You could use `.format` – whackamadoodle3000 Jun 25 '18 at 17:34
  • This would work the same if you replaced the "+" with a comma and removed the trailing space after "against". You could also use str.format as explained here: https://www.python-course.eu/python3_formatted_output.php – Neeldhara Jun 25 '18 at 17:35
  • Note the answer on the linked question that recommends f-strings. They're probably simplest way to format strings, but are only available in Python 3.6+ `f"Executing against {env}"` – Patrick Haugh Jun 25 '18 at 17:36

2 Answers2

1

Try this:

print('Executing against {}'.format(env))
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
1

The problem with + is that the second argument must be a string, otherwise an error is thrown. If that's not an issue, using + will work. However, there are other, usually more idiomatic ways:

1.) the print function can take multiple arguments, which get concatenated with a space:

print('Executing against', env)

2.) "old-style" interpolation:

print('Executing against %s' % env)

The right-hand side may also take multiple arguments in a tuple. So to protect against the possibility of the argument to be a tuple itself, you usually always put your variable in a tuple:

print('Executing against %s' % (env,))

3.) The more modern way is to use .format and its ecosystem (there's magic __format__ methods and whatnot you usually don't need to know about but gives you great flexibility):

print('Executing against {}'.format(env))

4.) Python 3.6 and upwards: Syntactic sugar for .format(). You can now directly put variables, and even whole expressions inside the string by making it a format-string (prefix it with f):

print(f'Executing against {env}')

Felk
  • 7,720
  • 2
  • 35
  • 65