Write rows in columns in file in Python [closed]

2019-09-02 19:15发布

I have sentences,in a form of a string, that look like this :

First sentence

            hund                    
barked      4.51141770734e-07
bit         0.0673737226603
dog         0.932625826198

Second sentence

            hyi                     
biid        6.12323423324e-07
bok         0.0643253
dyfs        0.514586321

and I want to write them into columns into a file like this :

            hund                                    hyi     
barked      4.51141770734e-07           biid        6.12323423324e-07
bit         0.0673737226603             bok         0.0643253
dog         0.932625826198              dyfs        0.514586321

Instead of having them like this :

            hund                    
barked      4.51141770734e-07
bit         0.0673737226603
dog         0.932625826198

            hyi                     
biid        6.12323423324e-07
bok         0.0643253
dyfs        0.514586321

Any ideas?

标签: python file row
2条回答
老娘就宠你
2楼-- · 2019-09-02 19:39

If it's string formatting you're after, you might want to look as str.ljust to make a string a certain length.

查看更多
女痞
3楼-- · 2019-09-02 19:48

Suppose you have two lists of lines, lines1 and lines2. If you have a string with multiple newlines, you can make a list of lines by calling .split('\n').

Then, you can format them into parallel columns with string formatting:

lines = ['{:<40}{:<40}'.format(s1, s2) for s1, s2 in zip(lines1, lines2)]

Example:

a = '''            hund                    
barked      4.51141770734e-07
bit         0.0673737226603
dog         0.932625826198'''.split('\n')
b = '''            hyi                     
biid        6.12323423324e-07
bok         0.0643253
dyfs        0.514586321'''.split('\n')
lines = ['{0:<40}{1:<40}'.format(s1, s2) for s1, s2 in zip(a,b)]
print '\n'.join(lines)

Output:

            hund                                    hyi                         
barked      4.51141770734e-07           biid        6.12323423324e-07           
bit         0.0673737226603             bok         0.0643253                   
dog         0.932625826198              dyfs        0.514586321                 
查看更多
登录 后发表回答