如何在Python中使用连接固定字符串和变量

时间:2013-08-21 04:09:12

标签: python string-concatenation

我想在主题中包含文件名'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

6 个答案:

答案 0 :(得分:36)

我猜你打算这样做:

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in python, use       ^ 

答案 1 :(得分:6)

试试

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

在python中重写+运算符以连接字符串。

答案 2 :(得分:4)

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

因此

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

并且您还必须在开始时导入sys

as

import sys

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

答案 3 :(得分:2)

variable=" Hello..."  
print (variable)  
print("This is the Test File "+variable)  

表示整数类型...

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

答案 4 :(得分:2)

我知道这有点旧,但是我想添加一个更新的答案,其中包含f字符串,这是Python 3.6版中引入的:

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

答案 5 :(得分:0)

使用python 3.6 +:

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