代码之家  ›  专栏  ›  技术社区  ›  Coby

在Python中前置字符串

  •  3
  • Coby  · 技术社区  · 7 年前

        lst = ['1234','2345']
        for x in lst:
            while len(x) < 5:
                x = '0' + x
        print(lst)
    

    理想情况下,这将打印[012345',02345']

    5 回复  |  直到 7 年前
        1
  •  13
  •   akuiper    7 年前

    您可以使用 zfill :

    在左边用零位数填充数字字符串s,直到给定 达到宽度

    lst = ['1234','2345']
    [s.zfill(5) for s in lst]
    # ['01234', '02345']
    

    或使用 format 填充和对齐

    ["{:0>5}".format(s) for s in lst]
    # ['01234', '02345']
    
        2
  •  3
  •   developer_hatch    7 年前

    由于python中的字符串是不可变的,因此您编写的代码无法完成这项工作,请参阅此处了解更多信息 Why doesn't calling a Python string method do anything unless you assign its output?

    在这种情况下,您可以这样列举:

    lst = ['1234','2345', "23456"]
    for i, l in enumerate(lst):
      if len(l) < 5:
        lst[i] = '0' + l
    print(lst)
    

    ['01234', '02345', '23456']

        3
  •  2
  •   blacksite    7 年前

    >>> ['0' * (5-len(x)) + x for x in lst]
    ['01234', '02345']
    

    或者 list map 尝试:

    >>> list(map(lambda x: '0' * (5-len(x)) + x, lst))
    ['01234', '02345']
    
        4
  •  1
  •   Coby    7 年前

    lst = ['1234','2345']
    newlst = []
    
    for i in lst:
        i = i.zfill(5)
        newlst.append(i)
    
    print(newlst)
    

        5
  •  0
  •   Dat Ha    7 年前

    您可以这样做:

    >>> lst = ['1234','2345']
    >>> lst = ['0' * (5 - len(i)) + i for i in lst]
    >>> print(lst)
    ['01234', '02345']