如何删除 python 3.7 中末尾的逗号?

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

我得到了什么

'Left 2, Right 4, Right 2, '

我想要的:

'Left 2, Right 4, Right 2'

我的代码:

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, '

不要把逗号放在最后。 str.join 方法专为您打造。它在分隔符上调用(如 ', '),并接受您想要集中的可迭代字符串。例如:

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)

最后一行可以使用map重写为

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

如果你想要一个非常难以辨认的单行(我不推荐,但是 python 写起来很容易):

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

甚至(最大限度地滥用 f 弦):

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

为了坚持你的计算机科学 101 已经教给你的东西,你可以改为在循环开始时将 ", " 附加到 comb 只有当 comb 不为空时字符串:

def get_combination(decoded):
    comb = ""
    for elm in decoded:
        if comb != "":
            comb += ", "
        if elm >= 0: 
            comb += "Right "
        else:
            comb += "Left "
        comb += str(abs(elm))
    return comb

或者如果您不想更新代码,可以使用 Strip 方法 https://docs.python.org/2/library/string.html

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.rstrip(", ")