在 Python 中将 int 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3944876/
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
Casting an int to a string in Python
提问by pythonTA
I want to be able to generate a number of text files with the names fileX.txt where X is some integer:
我希望能够生成多个名称为 fileX.txt 的文本文件,其中 X 是某个整数:
for i in range(key):
filename = "ME" + i + ".txt" //Error here! Can't concat a string and int
filenum = filename
filenum = open(filename , 'w')
Does anyone else know how to do the filename = "ME" + i part so I get a list of files with the names: "ME0.txt" , "ME1.txt" , "ME2.txt" , and etc
有没有其他人知道如何执行 filename = "ME" + i part 所以我得到一个文件列表,名称为: "ME0.txt" 、 "ME1.txt" 、 "ME2.txt" 等
采纳答案by Florian Mayer
x = 1
y = "foo" + str(x)
Please see the Python documentation: https://docs.python.org/2/library/functions.html#str
请参阅 Python 文档:https: //docs.python.org/2/library/functions.html#str
回答by Ferdinand Beyer
For Python versions prior to 2.6, use the string formatting operator %:
对于 2.6 之前的 Python 版本,请使用字符串格式化运算符%:
filename = "ME%d.txt" % i
For 2.6 and later, use the str.format()method:
对于 2.6 及更高版本,请使用以下str.format()方法:
filename = "ME{0}.txt".format(i)
Though the first example still works in 2.6, the second one is preferred.
尽管第一个示例在 2.6 中仍然有效,但首选第二个示例。
If you have more than 10 files to name this way, you might want to add leading zeros so that the files are ordered correctly in directory listings:
如果您有 10 个以上的文件以这种方式命名,您可能需要添加前导零,以便文件在目录列表中正确排序:
filename = "ME%02d.txt" % i
filename = "ME{0:02d}.txt".format(i)
This will produce file names like ME00.txtto ME99.txt. For more digits, replace the 2in the examples with a higher number (eg, ME{0:03d}.txt).
这将产生的文件名称,如ME00.txt到ME99.txt。如需更多数字,请将2示例中的 替换为更大的数字(例如,ME{0:03d}.txt)。
回答by Frédéric Hamidi
Either:
任何一个:
"ME" + str(i)
Or:
或者:
"ME%d" % i
The second one is usually preferred, especially if you want to build a string from several tokens.
通常首选第二个,特别是如果您想从多个令牌构建一个字符串。
回答by nmichaels
You can use str()to cast it, or formatters:
您可以使用str()强制转换它或格式化程序:
"ME%d.txt" % (num,)
回答by Tony Veijalainen
Here answer for your code as whole:
这是您的代码整体的答案:
key =10
files = ("ME%i.txt" % i for i in range(key))
#opening
files = [ open(filename, 'w') for filename in files]
# processing
for i, file in zip(range(key),files):
file.write(str(i))
# closing
for openfile in files:
openfile.close()

