Search code examples
pythonstringlistpython-3.7

How do I remove the comma at the end in python 3.7?


What I get

'Left 2, Right 4, Right 2, '

What I want:

'Left 2, Right 4, Right 2'

My code:

def get_combination(decoded):
    #(eg: get_combination([-2, 4, 2])
    #create an empty string
    comb = ""
    #For each elment in [decoded] check if the elm is < 0 or elm is >= 0
    for elm in decoded:
        if elm >= 0: 
            #if the elm is greater than  0 add to the string comb
            # So the string will read (eg:Right 2) 
            comb += "Right " + str(abs(elm)) + ", "
        elif elm < 0:
            #if the elm is less than 0 add to the string comb
            #So the string will read (eg: Left 4)
            comb += "Left "+ str(abs(elm)) + ", "
    return comb
    #it returns 'Left 2, Right 4, Right 2, '

Solution

  • Don't put commas until the end. The method str.join is made just for you. It is called on the separator (like ', '), and accepts an iterable of strings that you want to concentrate. For example:

    def get_combination(decoded):
        def encode(x):
            if x < 0:
                return f'Left {abs(x)}'
            return f'Right {x}'
        return ', '.join(encode(x) for x in decoded)
    

    The last line could be rewritten using map as

    return ', '.join(map(encode, decoded))
    

    If you want a really illegible one-liner (which I don't recommend, but python makes so easy to write):

    ', '.join(f'Left {abs(x)}' if x < 0 else f'Right {x}' for x in decoded)
    

    or even (abusing f-strings to the max):

    ', '.join(f'{"Left" if x < 0 else "Right"} {abs(x)}' for x in decoded)