❮ Python Glossary
String Concatenation
String concatenation means add strings together.
Use the +
character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z = x + y
print[z]
Try it Yourself »
Example
Merge variable a
with variable b
into variable c
:
a = "Hello"
b = "World"
c = a + b
print[c]
Try it Yourself »
Example
To add a space between them, add a " "
:
a = "Hello"
b = "World"
c = a + " " + b
print[c]
Try it Yourself »
For numbers, the +
character works as a mathematical operator:
Example
x = 5
y = 10
print[x + y]
Try it Yourself »
If you try to combine a string and a number, Python will give you an error:
Example
x = 5
y = "John"
print[x + y]
Try it Yourself »
Related Pages
Python Variables Tutorial Creating Variables Variable Names Assign Value to Multiple Variables Output Variables Global Variables
❮ Python Glossary
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 Aug 21, 2013 at 4:09
Shivam AgrawalShivam Agrawal
1,9494 gold badges24 silver badges41 bronze badges
3
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 Aug 21, 2013 at 4:10
Using f-strings which were introduced in Python version 3.6:
msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'
answered Dec 11, 2019 at 16:46
5
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 Jun 24, 2016 at 3:17
Smith JohnSmith John
1351 silver badge3 bronze badges
1
Try:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
The +
operator is overridden in Python to concatenate strings.
answered Aug 21, 2013 at 4:13
DotPiDotPi
3,7955 gold badges31 silver badges48 bronze badges
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 Aug 21, 2013 at 4:16
AntoAnto
6005 silver badges13 bronze badges
1
With Python 3.6 and later:
msg['Subject'] = f"Auto Hella Restart Report {sys.argv[1]}"
answered Jul 24, 2019 at 2:34
DoryxDoryx
3674 silver badges12 bronze badges
2