pythonarrayspython-3.xlistrepeat

How to repeat string in an array?


I want to repeat len(non_current_assets) times a string in an array. So I tried:

["",  "totalAssets", "total_non_current_assets" * len(non_current_assets), "totalAssets"]

But it returns:

['',
 'totalAssets',
 'total_non_current_assetstotal_non_current_assetstotal_non_current_assetstotal_non_current_assetstotal_non_current_assets',
 'totalAssets']

Solution

  • Place your str inside list, multiply, then unpack (using * operator) that is:

    non_current_assets = (1, 2, 3, 4, 5)  # so len(non_current_assets) == 5, might be anything as long as supports len
    lst = ["",  "totalAssets", *["total_non_current_assets"] * len(non_current_assets), "totalAssets"]
    print(lst)
    

    Output:

    ['', 'totalAssets', 'total_non_current_assets', 'total_non_current_assets', 'total_non_current_assets', 'total_non_current_assets', 'total_non_current_assets', 'totalAssets']
    

    (tested in Python 3.7)