How to concatenate a fixed string and a variable in Python

Question:

I want to include a file name, ‘main.txt’, in the subject. For that I am passing a file name from the command line. But I get an error in doing so:

python sample.py main.txt # Running 'python' with an argument

msg['Subject'] = "Auto Hella Restart Report "sys.argv[1]  # Line where I am using that passed argument

How can I fix this problem?

Asked By: Shivam Agrawal

||

Answers:

I’m guessing that you meant to do this:

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in Python, use       ^
Answered By: Brionius

Try:

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]

The + operator is overridden in Python to concatenate strings.

Answered By: DotPi

If you need to add two strings, you have to use the ‘+’ operator.

Hence

msg['Subject'] = 'your string' + sys.argv[1]

And also you have to import sys in the beginning.

As

import sys

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
Answered By: Anto
variable=" Hello..."
print (variable)
print("This is the Test File " + variable)

For an integer type:

variable = "  10"
print (variable)
print("This is the Test File " + str(variable))
Answered By: Smith John

With Python 3.6 and later:

msg['Subject'] = f"Auto Hella Restart Report {sys.argv[1]}"
Answered By: Doryx

Using f-strings which were introduced in Python version 3.6:

msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'
Answered By: Samwise Ganges
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.