将字符串转换为具有列的表格式

2024-09-28 01:27:40 发布

您现在位置:Python中文网/ 问答频道 /正文

The file name is studs.txt and this is what is inside:
12345 2 G400 Bart Simpson
12346 1 GH46 Lisa Simpson
12347 2 G401 Homer J Simpson
12348 4 H610 Hermione Grainger
12349 3 G400 Harry Potter
12350 1 G402 Herschel Shmoikel Krustofski
13123 3 G612 Wayne Rooney

x = input("Enter a filename: ")
try:
    o = open(x, "r")
    p = o.read()
    y = tuple(j for j in p.splitlines())
    m = " ".join(map(str, y))
    print(m) 
    o.close()
except IOError as e :
    print("File Does Not Exist")

当我运行此代码时,它将导入此文件“螺柱.txt“并将其放入字符串中,但我希望将该字符串转换为表格格式并以特定布局显示,以便使其看起来像这样:

Simpson, Bart    12345    G400   2
Simpson, Lisa    12346    G401   1

等等


Tags: andthe字符串nametxtisthisfile
1条回答
网友
1楼 · 发布于 2024-09-28 01:27:40

我想你可以这样做:

try:
    o = open(x, "r")
    p = o.read()
    y = tuple(j.split() for j in p.splitlines())
    #m = " ".join(map(str, y))
    for v1,v2,v3,fname,*rest_of_name in y:
        #print(v1,v2,v3,fname,*rest_of_name)

        if int(v1) != some_year:  
            continue;

        print("{:<30} {:<10} {:<5} {:<5}".format(fname + ', ' +  ' '.join(rest_of_name), v1,v3, v2))
    o.close()
except IOError as e :
    print("File Does Not Exist")

这张照片:

Bart, Simpson                  12345      G400  2    
Lisa, Simpson                  12346      GH46  1    
Homer, J Simpson               12347      G401  2    
Hermione, Grainger             12348      H610  4    
Harry, Potter                  12349      G400  3    
Herschel, Shmoikel Krustofski  12350      G402  1    
Wayne, Rooney                  13123      G612  3   

相关问题 更多 >

    热门问题