我有三个字符串,我想对齐它们

时间:2018-02-02 20:27:43

标签: python python-3.x join format

我有三个字符串:s1s2edit action。它们如下:

s1 = kevin josh left at three for - car.
s2 = kevin - left at one - for his car.
edit action =  d      s   i

我想像这样对齐它们:

s1          = kevin josh left at three for  -  car.
s2          = kevin  -   left at  one  for his car.
edit action =        d             s        i    

下面是我使用格式和连接将它们对齐在一起的代码:

print(" s1 = ", '{0}'.format(" ".join(s1)))
print(" s2 = ",'{0}'.format(" ".join(s2)))
print("edit action = ",'{0}'.format(" ".join(edit action)))

2 个答案:

答案 0 :(得分:1)

s1 = "kevin josh left at three for - car."
s2 = "kevin - left at one - for his car."
editaction = "  d      s   i".replace(" ","")
maxstring=max(len(s1),len(s2))
c1=len("edit action ")
c2='{:'+str(c1)+'}  {:'+str(maxstring)+'} ' 
print(c2.format(" s1 ", "= "+s1))
print(c2.format(" s2 ", "= "+s2))
w1=s2.find("-") #d
w2=s2.find("one")-w1 #s
w3=s2.find("his")-w2-w1  #i
print(c2.format(" edit action","= " +
editaction.replace(editaction[0]," "*w1+editaction[0]).replace(editaction[1]," 
"*w2+editaction[1]).replace(editaction[2]," "*w3+editaction[2])))

答案 1 :(得分:0)

the Python docs

中尝试以下格式说明符
'{:>max_width}'.format('right aligned')

其中max_width可以选择为最长左手边的长度。