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?
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 ^
Try:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
The +
operator is overridden in Python to concatenate strings.
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]
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))
With Python 3.6 and later:
msg['Subject'] = f"Auto Hella Restart Report {sys.argv[1]}"
Using f-strings which were introduced in Python version 3.6:
msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'
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?
I’m guessing that you meant to do this:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in Python, use ^
Try:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
The +
operator is overridden in Python to concatenate strings.
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]
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))
With Python 3.6 and later:
msg['Subject'] = f"Auto Hella Restart Report {sys.argv[1]}"
Using f-strings which were introduced in Python version 3.6:
msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'