[英]Python Turn something inside a string to a variable
I want to do an output name for a file and the input will/should be like this:我想为文件做一个输出名称,输入将/应该是这样的:
"seriesName Episode epNr 720p"
and I want to turn the seriesName and the epNr to variables I set.我想将seriesName和epNr 转换为我设置的变量。 For example:
例如:
seriesName="Mr. Robot"
epNr=10
and if I do print(output), the output should be如果我打印(输出),输出应该是
"Mr. Robot Episode 10 720p"
Try using str.replace
:尝试使用
str.replace
:
myString = "seriesName Episode epNr 720p"
replacedString = myString.replace('seriesName', 'Mr. Robot').replace('epNr', '10')
print(replacedString)
Or better yet, use str.format
with keyword arguments:或者更好的是,使用带有关键字参数的
str.format
:
In [1]: myString = "{seriesName} Episode {epNr} 720p"
In [2]: myString.format(seriesName='Mr. Robot', epNr='10')
Out[3]: 'Mr. Robot Episode 10 720p'
A more general way of achieving the same:实现相同目标的更一般方法:
seriesName="Mr. Robot"
epNr=10
print "{} Episode {} 720p".format(seriesName,epNr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.