简体   繁体   中英

how to use concatenate a fixed string and a variable in Python

I want to include file name 'main.txt' in the subject for that I am passing file name from command line. but getting error in doing so

python sample.py main.txt #running python with argument 

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

I'm guessing that you meant to do this:

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in python, use       ^ 
variable=" Hello..."  
print (variable)  
print("This is the Test File "+variable)  

for integer type ...

variable="  10"  
print (variable)  
print("This is the Test File "+str(variable))  

我知道这有点旧,但我想用 Python 3.6 版中引入的 f-strings 添加一个更新的答案:

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

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]

使用 python 3.6+:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM