python - 将列表中的字符串填充为相同长度

标签 python string list

我有一个从文件中读取的字符串列表。每个元素都是一行文件。 我想要一个长度相同的字符串数组。我想找到最长的字符串并重新格式化其他字符串,只要最长的字符串(末尾有空格)。 现在我找到了最长的一个。但我不知道如何重新格式化其他字符串。有人可以帮帮我吗?

with open('cars') as f:
    lines = f.readlines()
lines = [line.rstrip('\n') for line in open('cars')]
max_in=len(lines[0])
for l in lines:
    print (str(len(l))+" "+str(max_in))
    if max_in < len(l):
        max_in=len(l)
print max_in

最佳答案

从这里开始:

In [546]: array = ['foo', 'bar', 'baz', 'foobar']

使用max求最大字符串的长度:

In [547]: max(array, key=len) # ignore this line (it's for demonstrative purposes)
Out[547]: 'foobar'

In [548]: maxlen = len(max(array, key=len))

现在,使用列表理解并向左填充:

In [551]: [(' ' * (maxlen - len(x))) + x for x in array]
Out[551]: ['   foo', '   bar', '   baz', 'foobar']

关于python - 将列表中的字符串填充为相同长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45120703/

相关文章:

Python 单元测试 : how to reuse the TestCase. 断言函数

C++字符串类效率

java - 并行迭代两个 String[] 数组?

python - 比较 pandas DataFrame 列中的多个字符串

c++ - 列表迭代器错误 : "no match for operator+" ,

python - 我应该在我的 setup.py 中有条件地要求 simplejson 吗?

java - Raspberry Pi MAX31865 Python 到 Java 的转换

python - 使用窗口函数在 Postgres 上使用 SqlAlchemy 限制查询

C++ 11 STL 列表 = 和 != op 未定义

c++ - 列表 vector