56

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?

3
  • 1
    It's almost always a good idea to include the stack trace - it's there to help you debug! Commented Aug 21, 2013 at 4:12
  • That was four years after Stack Overflow launched. What is the canonical question? This must have been asked within the first few days. Commented Mar 27, 2022 at 16:42
  • The error message may be something like "SyntaxError: invalid syntax". Commented Mar 27, 2022 at 16:47

6 Answers 6

66

I'm guessing that you meant to do this:

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in Python, use       ^
Sign up to request clarification or add additional context in comments.

Comments

28

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

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

4 Comments

Is this the recommended way over the plus concatenator?
What is the name of the Python feature used here? f-strings?
This seems to repeat Doryx's answers (five months prior). What is the difference? Is there a real difference? (Single quotes vs. double quotes.)
No difference in single or double quotes, most people like to use double quotes in strings so that if you have an apostrophe you don't have to escape it, "I'm Doryx" instead of 'I\'m Doryx'
15
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))

1 Comment

But the question is not about integers, only two strings.
7

Try:

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

The + operator is overridden in Python to concatenate strings.

Comments

5

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]

1 Comment

It must be msg['Subject'] = 'your string' + sys.argv[1] in the first example otherwise you get a syntax error.
5

With Python 3.6 and later:

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

2 Comments

What is the name of the Python feature used here? f-strings?
Yes! Also see here: peps.python.org/pep-0498 for the terminology. Thanks for the edit by the way!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.