python - 在列表元素中添加空格(PY)

标签 python

我有一个问题:

我有一个包含不同长度元素的列表: det_slopes_JKH = ['Superpipe Bolgen','JatzPark','Avalanch Training Center','Bräma schwer']

我想在较短的单词中添加空格 ' ',目的是让列表中的所有元素具有相同的长度。

det_slopes_JKH2 = []
for element in det_slopes_JKH:
     if len(element) < len(element[2]:
         det_slopes_JKH2.append(element + ' ')

谢谢

最佳答案

您的目标不是很明确,但我假设您希望所有字符串的长度都相同。

这会为每个字符串添加一个空格,直到所有字符串的长度都相同(最长字符串的长度):

def equalize_lengths(l):
    length = len(max(l, key=len))
    return [e.ljust(length) for e in l]

关于python - 在列表元素中添加空格(PY),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27167876/

相关文章:

python - 电子邮件错误.HeaderParseError : header value appears to contain an embedded header:

python - 使用 ruamel.yaml 加载和转储多个 yaml 文件 (python)

python - Django 设置.py 错误 : Import by filename is not supported

python - python中的phpMyAdmin等价物?

python - 创建一个程序,如果按字典顺序输入三个单词则打印 true

python cdll 找不到模块

python - 导入 BERT : module 'tensorflow._api.v2.train' has no attribute 'Optimizer' 时出错

python - SQL炼金术 : eager loading relationships of relationships of relationship

python - Pandas - 将 CSV 读入数据框,其中一列具有不同数量的子列

python - 如果值具有 NaN,则在 pandas 中使用 bootstrap_plot 时出错