【问题标题】:I have three strings and I want to align them我有三个字符串,我想对齐它们
【发布时间】:2018-02-02 20:27:42
【问题描述】:

我有三个字符串: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    

下面是我的代码,我使用了 format 和 join 来将它们对齐:

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

【问题讨论】:

  • dsijosh-threeone- 和 @987654333355 有什么关系? /跨度>
  • 它们是将字符串 s1 转换为字符串 s2 所需的操作。 d代表删除一个词,s代表或替换一个词,i代表插入一个词。

标签: python python-3.x join format


【解决方案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])))

【讨论】:

    【解决方案2】:

    尝试以下格式说明符,来自the Python docs

    '{:>max_width}'.format('right aligned')
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多