python - 以相同的宽度打印 ":"右侧的所有内容

标签 python python-2.7

我正在编写一个小脚本,它应该格式化一些字符串,以便它们更具可读性。输入是一个列表,列表中包含字符串。输入可能看起来像这样(注意:这与图像中的输入相同,只是图像更好地对比了输入和输出):

['last name: Callum', 'first name: Brian', 'middle name: Mosbey', 'balance: $0']

每个字符串中都有一个:。我希望 : 右侧的所有文本以相同的宽度打印,以便更容易阅读信息。我想要的输出是这样的(注意:我用方法 2 得到了这个,但用方法 1 没有):

['last name:   Callum', 'first name:  Brian', 'middle name: Mosbey', 'balance:     $0']

这是我解决问题的方法:

  1. 首先我们遍历字符串列表并在另一个列表中存储在可以找到 : 的索引处

  2. 首先我们找出哪个字符串的 highest_index:

  3. 我们再次遍历字符串列表(新的迭代),我们计算的当前索引的差异:的当前索引highest_index

  4. (仍在迭代中)在我们找到 的地方的右边: 我们插入 ' ' * difference

问题:我有这个解决方案的 2 个实现。方法 1 较短,但不起作用。方法 2 更长,但至少有效。为什么方法 1 不起作用?

enter image description here


代码:

def even_spacing(lst):
    new_lst = []  # list for the final output
    index_colon = []  # list of the indexs where ':' is found, for each line

    # find where the ':' in each line
    for line_string in lst:
        index_colon.append(line_string.find(':'))
    highest_index = max(index_colon)  # the highest index ':' can be found at in any of the lines

    # we add the extra spaces
    for index, s in enumerate(lst):
        difference = highest_index - index_colon[index]  # how many spaces will be needed


        # METHOD 1 not working, less code
        # new_lst.append(''.join(list(s).insert(index_colon[index]+1, ' '*difference)))  # insert at the index we found the proper number of spaces

        # METHOD 2, working, but more code
        list_letters = list(s)
        list_letters.insert(index_colon[index]+1, ' '*difference)
        new_lst.append(''.join(list_letters))

    return new_lst

test = ['last name: Callum', 'first name: Brian', 'middle name: Mosbey', 'balance: $0']
print even_spacing(test)

pastebin

最佳答案

列表的 insert 方法就地起作用(改变列表,并且不返回它)并返回 None:

>>> a = [1,2,3]
>>> b = a.insert(1, "inserted")
>>> print a
[1, 'inserted', 2, 3]
>>> print b
None

所以你不能链接涉及.insert的操作,这就是为什么

''.join(list(s).insert(index_colon[index]+1, ' '*difference))

不会工作。这基本上是 ''.join(None)

您的第二种方法有效,因为您正在调用 insert 但没有尝试处理它返回的内容。

关于python - 以相同的宽度打印 ":"右侧的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21499779/

相关文章:

python - 存储 int 显示标签?枚举

python - 在 Django 中为每个模型设置数据库

python - Python 3 中的连接列表

python - 使用 Python Selenium 检查元素是否存在

python-2.7 - AWS Lambda - 在内存中生成 CSV 并将其作为电子邮件附件发送

python - 如何在树莓派中设置相机拍摄黑白图像?

python-2.7 - 无法使用 psycopg2 从 Amazon Redshift 读取数据

python-2.7 - 如何在pytorch中为不同层设置不同的学习率?

python - 比较列表中的文件

python - 查找错误 : Resource 'corpora/stopwords' not found