【问题标题】:Adding blank spaces to a list of strings at a specific position将空格添加到特定位置的字符串列表
【发布时间】:2020-08-15 00:27:31
【问题描述】:

我正在尝试处理字符串列表,以获取包含 8 个字符的所有字符串。如果一个字符串少于 8 个字符,我会根据需要填充尽可能多的空格,以便在最后 4 个字符之前获得一个 8 个字符长的字符串。我编写了以下函数并尝试将其应用于字符串列表,但得到了一个包含 None 值的列表。

def lengthstring(string):
    if len(string) == 5:
        new_string = string[0] + "   " + string[1:5]
    elif len(string) == 6:
        new_string = string[0:2] + "  " + string[2:6]
    elif len(string) == 7:
        new_string = string[0:3] + " " + string[3:7]
    else:
        new_string = string

lp = ['7C246', '7B8451', 'NDKW0745', '5B06833']

labels_with_eight_characters = [lengthstring(string) for string in lp]

谢谢!

【问题讨论】:

  • 没有return声明

标签: python string list function list-comprehension


【解决方案1】:

以防万一您需要更简洁的代码版本:

def lengthstring(string):
    return (
        string if len(string) >= 8
        else string[:-4] + ' ' * (8 - len(string)) + string[-4:])


labels_with_eight_characters = list(map(lengthstring, lp))
print(labels_with_eight_characters)

打印出来:

['7   C246', '7B  8451', 'NDKW0745', '5B0 6833']

【讨论】:

    【解决方案2】:

    这是因为您没有在 lengthstring 函数中返回值。在new_string = string 之后,添加return new_string,您的代码应该可以正常运行。

    【讨论】:

    • 谢谢! :D 很高兴这很容易 :D
    【解决方案3】:

    使用rjust...

    for loc in lp:
        print(loc.rjust(8, ' '))
    

    【讨论】:

    • OP 希望最后 4 个字符完好无损。
    • 明白了......只是不清楚为什么空格在中间。有时我会为简单的问题创建复杂的解决方案。
    猜你喜欢
    • 2020-02-26
    • 1970-01-01
    • 2014-04-04
    • 2023-03-22
    • 1970-01-01
    • 2018-03-13
    • 2021-09-25
    • 2017-09-01
    • 1970-01-01
    相关资源
    最近更新 更多