Shivam Agrawal
Shivam Agrawal

Reputation: 2113

How to concatenate a fixed string and a variable in Python

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?

Upvotes: 56

Views: 325160

Answers (6)

Samwise Ganges
Samwise Ganges

Reputation: 552

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

msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'

Upvotes: 28

Doryx
Doryx

Reputation: 387

With Python 3.6 and later:

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

Upvotes: 5

Smith John
Smith John

Reputation: 135

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

Upvotes: 13

Anto
Anto

Reputation: 610

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]

Upvotes: 5

DotPi
DotPi

Reputation: 4137

Try:

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

The + operator is overridden in Python to concatenate strings.

Upvotes: 7

Brionius
Brionius

Reputation: 14118

I'm guessing that you meant to do this:

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

Upvotes: 66

Related Questions