在 Python 中将 int 转换为字符串
我希望能够生成多个名称为 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')
是否有其他人知道如何执行 filename = "ME" + i 部分,以便我获得具有这些名称的文件列表:“ME0.txt”、“ME1.txt”、“ME2.txt”等
I want to be able to generate a number of text files with the names fileX.txt where X is some integer:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用
str()
来转换它,或格式化程序:You can use
str()
to cast it, or formatters:这是您的整个代码的答案:
Here answer for your code as whole:
适用于 Python 3 和 Python 2.7
使用格式
{:03d}
获得 3 位数字并以 0 开头,这是一个很好的技巧,可以让文件在资源管理器中查看时以正确的顺序显示。将括号留空{}
以实现默认格式。Works on Python 3 and Python 2.7
Use format
{:03d}
to have 3 digits with leading 0, it's a great trick to have the files appear in the right order when looking at them in the explorer. Leave brackets empty{}
for default formatting.请参阅Python文档: https://docs.python.org/3/库/functions.html#str
Please see the Python documentation: https://docs.python.org/3/library/functions.html#str
对于 2.6 之前的 Python 版本,请使用 字符串格式化运算符
%
:对于 2.6 及更高版本,请使用
str .format()
方法:虽然第一个示例在 2.6 中仍然有效,但第二个示例是首选。
如果您有超过 10 个文件以这种方式命名,您可能需要添加前导零,以便文件在目录列表中正确排序:
这将生成类似
ME00.txt
到的文件名ME99.txt
。如需更多数字,请将示例中的2
替换为更大的数字(例如ME{0:03d}.txt
)。For Python versions prior to 2.6, use the string formatting operator
%
:For 2.6 and later, use the
str.format()
method:Though the first example still works in 2.6, the second one is preferred.
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:
This will produce file names like
ME00.txt
toME99.txt
. For more digits, replace the2
in the examples with a higher number (eg,ME{0:03d}.txt
).要么:
要么:
通常首选第二个,特别是当您想从多个标记构建字符串时。
Either:
Or:
The second one is usually preferred, especially if you want to build a string from several tokens.