python - 如何简单地将分号与 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]:])
有什么简单的实现方法吗?谢谢你。
解决方案
尝试对齐输出时,函数喜欢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]
推荐阅读
- python - 在列中逐个单元格比较是输入字符串的子字符串
- python - ValueError:无法将字符串转换为浮点数:'2.500.000\ufeff'
- gulp - 尝试使用 gulp 使 browsersync 在 vagrant 中工作
- javascript - 覆盖两个 base64 图像 url 并将它们保存为 Javascript 中的单个图像
- c - 如何在“输入模式”下将控制器“STM8S103F3”的引脚“PD6 和 PD5”配置为低状态(电压电平 0)
- flutter - Flutter:为 MaterialApp 类应用渐变背景
- bash - 从 Bash 中的特定行反向搜索模式
- java - Java 中的 AWS Lambda 请求 gzip 编码
- flutter - 如何在 Flutter Provider 中正确初始化 Future
- python - wrapInstance 后 PYQT Maya QMouseEvent 将不起作用