Search code examples
pythonvalidation

python list get values validate position out of ranges


I have a list in Python. Then I want to print the data in each position of the list but if this position is empty replace it with a blank space:

["abcd", "12", "x"] => "a1xb2 c  d  "

I think to make a loop for validating the data in each position. But, when a position in the list is empty, I can't make a validation because I obtain a mistake of index out of range, then it is impossible to make a validation.

How can I get the values of a list in Python in a range of the list that probably can be empty for make a validation.


Solution

  • izip_longest from itertools is your friend. It uses the longest iterable (string here) and replaces the missing characters by the fill value that can be set to the desired space:

    from itertools import izip_longest
    
    def f(strings):
        return ''.join(
            map(lambda x: ''.join(x), izip_longest(*strings, fillvalue=' '))
        )
    
    
    a = ["abcd", "12", "x"]
    
    print(repr(f(a)))
    

    Result:

    'a1xb2 c  d  '
    

    A variant with chain instead of map and the second join.

    def f(strings):
        return ''.join(
            chain(*izip_longest(*strings, fillvalue=' '))
        )
    

    Intermediate steps of the last method applied on array a:

    from pprint import pprint
    
    a1 = izip_longest(*a, fillvalue=' ')
    print('# After izip_longest:')
    pprint(list(a1))
    
    print('# After chain:')
    a1 = izip_longest(*a, fillvalue=' ')
    a2 = chain(*a1)
    pprint(list(a2))
    
    a1 = izip_longest(*a, fillvalue=' ')
    a2 = chain(*a1)
    a3 = ''.join(a2)
    print('# Result:')
    pprint(a3)
    

    Result:

    # After izip_longest:
    [('a', '1', 'x'), ('b', '2', ' '), ('c', ' ', ' '), ('d', ' ', ' ')]
    # After chain:
    ['a', '1', 'x', 'b', '2', ' ', 'c', ' ', ' ', 'd', ' ', ' ']
    # Result:
    'a1xb2 c  d  '