首页 > 解决方案 > 如何简单地将分号与 Python 中的字符串对齐?

问题描述

我需要在字符串中对齐分号。例如:

Input:
  1-1: abc
  1-2-1: defghi
  1-2-1a: jklmnopqr
  1-2-1a-1-1-1a: stuvwxyz

Ouput:
  1-1          : abc
  1-2-1        : defghi
  1-2-1a       : jklmnopqr
  1-2-1a-1-1-1a: stuvwxyz

以下是我的解决方案。

strs = ['1-1: abc', '2-2-2: defghi', '3-3-3b: jklmnopqr', '1-2-1a-1-1-1a: stuvwxyz']
lengths = [s.find(':') for s in strs]
for i, s in enumerate(strs):
  if lengths[i] == -1:
    new_strs.append(s)
  else:
    new_strs.append(s[:lengths[i]] + ' ' * (max(lengths) - lengths[i]) + s[lengths[i]:])

有什么简单的实现方法吗?谢谢你。

标签: python

解决方案


尝试对齐输出时,函数喜欢ljust和是你的朋友:rjust

>>> aligned = [f"{s.split(':')[0].ljust(max(s.index(':') for s in strs))}:{s.split(':')[1]}" for s in strs]
>>> print("\n".join(aligned))
1-1          : abc
2-2-2        : defghi
3-3-3b       : jklmnopqr
1-2-1a-1-1-1a: stuvwxyz

或者不那么紧凑:

>>> i = max(s.index(":") for s in strs)
>>> cols = [s.split(":") for s in strs]
>>> aligned = [f"{c[0].ljust(i)}:{c[1]}" for c in cols]

推荐阅读