44

我想在主题中包含文件名“main.txt”,因为我从命令行传递文件名。但这样做会出错

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
4

6 回答 6

58

我猜你打算这样做:

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in python, use       ^ 
于 2013-08-21T04:10:47.300 回答
11
variable=" Hello..."  
print (variable)  
print("This is the Test File "+variable)  

对于整数类型...

variable="  10"  
print (variable)  
print("This is the Test File "+str(variable))  
于 2016-06-24T03:17:10.073 回答
9

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

msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'
于 2019-12-11T16:46:00.437 回答
7

尝试:

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

运算符在 python中+被覆盖以连接字符串。

于 2013-08-21T04:13:13.087 回答
5

如果您需要添加两个字符串,则必须使用“+”运算符

因此

msg['Subject'] = 'your string' + sys.argv[1]

而且你必须在开始时导入 sys

作为

import sys

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
于 2013-08-21T04:16:34.077 回答
1

使用 python 3.6+:

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

于 2019-07-24T02:34:35.780 回答