如何在 Python 中使用连接固定字符串和变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18348717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use concatenate a fixed string and a variable in Python
提问by Shivam Agrawal
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
我想在主题中包含文件名“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
采纳答案by Brionius
I'm guessing that you meant to do this:
我猜你打算这样做:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in python, use ^
回答by DotPi
Try:
尝试:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
The +
operator is overridden in python to concatenate strings.
该+
运营商在Python重写连接字符串。
回答by Anto
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 begining
而且你必须在开始时导入 sys
as
作为
import sys
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
回答by Smith John
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))
回答by Doryx
With python 3.6+:
使用 python 3.6+:
msg['Subject'] = f"Auto Hella Restart Report {sys.argv[1]}"
msg['Subject'] = f"Auto Hella Restart Report {sys.argv[1]}"
回答by Samwise Ganges
I know this is a little old but I wanted to add an updated answer with f-strings which were introduced in Python version 3.6:
我知道这有点旧,但我想用 Python 3.6 版中引入的 f-strings 添加一个更新的答案:
msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'