简体   繁体   English

使用 python 以特定格式打印字符串中的数字

[英]Print numbers in a string in specific format using python

I was to be able to create a file using python which has data in the specific format shown below.我能够使用 python 创建一个文件,该文件具有如下所示的特定格式的数据。 It starts from 00000# where # is 1 and goes all the way to 100000 .它从#1的 00000# 开始,一直到100000 The same number is present in each line before and after the text My Team .在文本My Team之前和之后的每一行中都存在相同的数字。

#output file
000001 My Team 000001
000002 My Team 000002
...all the way to
100000 My Team 100000

I am not sure on how to do this format creation in python.我不确定如何在 python 中创建这种格式。 I know it is something simple but I am a bit lost on how to proceed.我知道这很简单,但我对如何进行有点迷茫。 I am very new to python and I would appreciate if anyone can give me some guidance on this.我对 python 很陌生,如果有人能给我一些指导,我将不胜感激。

Thank you to all.谢谢你们。

If you're looking to make sure that a number always has six digits, you can do that with something like this如果你想确保一个数字总是有六位数字,你可以用这样的东西来做到这一点

def leadingZeros(num, length):
    out_str = str(num);
    while len(out_str) < length:
        out_str = "0" + out_str;
    return out_str;

You can use string formatting to achieve this您可以使用字符串格式来实现这一点

output_string = ''.join([f'{i:06d} My Team {i:06d}\n'for i in range(1, 100001)])

Alternatively using zfill或者使用zfill

output_string = ''.join([f'{str(i).zfill(6)} My Team {str(i).zfill(6)}\n'for i in range(1, 100001)])

You can try f-strings added in python 3.6:您可以尝试在 python 3.6 中添加的f-strings

PADDING = 6

with open('test.txt', 'w') as fh:
    for i in range(1, 100001):
        print(f'{i:0{PADDING}d} My Team {i:0{PADDING}d}', file=fh)

OUTPUT: OUTPUT:

000001 My Team 000001
000002 My Team 000002
...
100000 My Team 100000

Another method would be to usestr.zfill (zfill stands from zero-fill):另一种方法是使用str.zfill (zfill 代表零填充):

>>> i = 1
>>> f'{str(i).zfill(PADDING)} My Team {str(i).zfill(PADDING)}'
000001 My Team 000001

If you want to print the contents of the file which are already in that format then如果要打印已经采用该格式的文件内容,那么

with open('file.txt','r') as f:
      file_data=f.read()
      l=file_data.split("\n")
      print(*l)

If you want create a file like that then you can use, place the file the same directory as you code is in如果你想创建一个这样的文件,那么你可以使用,将文件放在与你的代码相同的目录中

with open('test.txt','w') as myfile:
for i in range(1,100001):
    print("{:0>6d} My team {:0>6d}".format(i,i),file=myfile)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM