传入为空时如何避免“ 1”

时间:2019-03-21 06:09:37

标签: python python-3.x python-2.7

当传入2和传入3不为空时我想要结果,那么应该避免在传入1和传入4之间打印两个'1'。

def string_con(self,combined):
    if combined is none:
       return '1'
    else:
       return str(combined)

if incoming['col1'] or incoming['col1'] or incoming['col3'] or incoming['col4']:    
combined = self.string_con(incoming['col1'])+'1'+self.string_con(incoming['col2'])+'1'+self.string_con(incoming['col3'])+'1'+self.string_con(incoming['col4'])
Input1 : incoming['col1']=a incoming['col4']=d
Output1: a1111d 
Expected output1:a1d 
Input2: incoming['col1']=a incoming['col2']=b 
Output2: a1b11 
Expected output2:a1b

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法吗?

req_keys = ['col1', 'col2', 'col3', 'col4']
all_list = [incoming[i] for i in req_keys]
all_list = [i for i in all_list if i]
print('1'.join(all_list))

示例:

incoming = {}
incoming['col1'] = 'a'
incoming['col2'] = None
incoming['col3'] = 'c'
incoming['col4'] = None

输出:

a1c

另一个例子:

incoming = {}
incoming['col1'] = 'a'
incoming['col2'] = None
incoming['col3'] = None
incoming['col4'] = 'd'

输出:

a1d