gpt4 book ai didi

Python 创建范围 000 到 999

转载 作者:行者123 更新时间:2023-11-30 23:24:59 26 4
gpt4 key购买 nike

我正在使用 bin 编号编写 Python 代码,然后创建一个像这样的数字列表

bin = "377731"
range(00000, 99999)

for i in range(len(bin)):
target = open('{0}.txt'.format(bin), 'a') ## a will append, w will over-wri$
target.write("{0}{1}000".format(bin,i) + "\n")
target.close()

Python这样显示列表的问题

3777311000

我需要它这样写

3777310000100

脚本在达到数字 5 后也会停止

有什么帮助吗?

谢谢

最佳答案

您的代码中有一些内容需要更改:

  • 您已将 bin 定义为值为 377731 的字符串。该字符串的长度是 6,这就是循环在 5 之后停止的原因。

  • 此外,bin是Python中的内置函数,因此最好不要将其用作变量的名称。

  • 在循环中打开和关闭文件是一种矫枉过正的行为。

试试这个:

bin_suffix = "377731"
target = open('{0}.txt'.format(bin_suffix), 'a') ## a will append, w will over-wri$
for i in range(99999):
target.write('{}{}'.format(bin_suffix, str(i).zfill(7)) + "\n")
target.close()

zfill是一个字符串函数,用零填充字符串的指定长度。在您的情况下,您需要 377731 之后有 7 位数字,因此您指定 7 作为 zfill

的参数

希望这有帮助。

关于Python 创建范围 000 到 999,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23166772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com