Search code examples
pythonloopsfor-loopif-statementnested-loops

I want to create elements of a list where each element comes from a satisfied nested for if loop statement


str1 ="John000Doe000123"

list1 = []

for i in str1:
  if i == "0":
    continue
    
  
  list1.append(i)

print(list1)

OUTPUT: ['J', 'o', 'h', 'n', 'D', 'o', 'e', '1', '2', '3']

but the output that I want is:

OUTPUT: ['John' , 'Doe' , '123']


Solution

  • You could split your string at character '0' and seek only valid entries from there:

    str1 ="John000Doe000123"
    
    print([name for name in str1.split('0') if name])
    # ['John', 'Doe', '123']