Created
November 21, 2014 12:50
-
-
Save 10nin/321ce195dc5216c8df48 to your computer and use it in GitHub Desktop.
二つの文字列を水平方向にpretty printな感じで接続するスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _justify_list(list1, list2): | |
"""短いほうのリストに空要素を追加して、リストの長さをそろえる""" | |
short_list = min(list1, list2, key=len) | |
c = max(len(list1), len(list2)) - len(short_list) | |
for i in range(0, c): | |
short_list.append('') | |
return list1, list2 | |
def _join_str_list(parent_list, child_list, margin): | |
"""空白で桁をそろえつつ、文字列のリストを行単位で結合""" | |
row_length = len(max(parent_list, key=len)) | |
parent_list, child_list = _justify_list(parent_list, child_list) | |
return [x + (' ' * (row_length - len(x) + margin)) + y for (x, y) in zip(parent_list, child_list)] | |
def join_text(text1, text2, margin=2): | |
"""テキストを水平結合""" | |
if text1 == '': | |
return text2 | |
str = '' | |
for l in _join_str_list(text1.split('\n'), text2.split('\n'), margin): | |
str += '\n' + l | |
return str.strip() | |
if __name__ == '__main__': | |
# リスト1のほうが行数が少なく, リスト2が空行を含むパターン | |
str1="""hello | |
fugafugahogehoge | |
foobar""" | |
str2="""world | |
test line | |
other text | |
""" | |
print(join_text(str1,str2)) | |
print('\n') | |
# リスト1のほうが行数が多いパターン | |
str1="""line1_ | |
line2__ | |
line3___ | |
line4____ | |
line5_____""" | |
str2="""short | |
line""" | |
print(join_text(str1,str2)) | |
print('\n') | |
# リスト1とリスト2の行数が同じパターン | |
str1="""line1_ | |
line2__ | |
line3___ | |
line4____ | |
line5_____""" | |
str2=str1 | |
print(join_text(str1,str2)) | |
print('\n') | |
# リスト1が空のパターン | |
str1="""""" | |
str2="""line1_ | |
line2__ | |
line3___ | |
line4____ | |
line5_____""" | |
print(join_text(str1,str2)) | |
print('\n') | |
# リスト2が空のパターン | |
str1="""line1_ | |
line2__ | |
line3___ | |
line4____ | |
line5_____""" | |
str2="""""" | |
print(join_text(str1,str2)) | |
print('\n') | |
# 3つのリストを結合するパターン | |
str1="""first list | |
line1 | |
line2__ | |
line3_ | |
line4**** | |
line5""" | |
str2="""second list | |
line1******* | |
line2*******""" | |
str3="""third list | |
line1 | |
line2 | |
line3""" | |
str=join_text(str1,str2) | |
print(join_text(str,str3)) | |
print('\n') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment