While loop to print out every character but "C" in the string

Viewed 61

I need to write a while loop that iterates through an entire string, but skips all the C's in the string. My current code just runs forever, and I can't get any sort of traceback because of it.

Here's what I have right now:

DNA = 'GTTGATGTAGCTTATATAAAGCAAGGCACTGAAAATGCCTAGATGAGTCATAGACTCCATAAACAACAGGTTTGGTCCCGGC'
x = 0
Part2 = []
while(x < len(DNA)):
  if DNA[x] != 'C':
    Part2.append(DNA[x])
    x = x + 1
  else:
    continue
print("Part 2: ", Part2)
4 Answers

This can be much simpler:

print([c for c in DNA if c != 'C'])

Or, if you want a string:

print(''.join([c for c in DNA if c != 'C']))

A similar approach (proposed by @Barmar):

print(DNA.replace('C', ''))

Your else:continue blocks the counter x from advancing:

DNA = 'GTTGATGTAGCTTATATAAAGCAAGGCACTGAAAATGCCTAGATGAGTCATAGACTCCATAAACAACAGGTTTGGTCCCGGC'
x = 0
Part2 = []
while(x < len(DNA)):
  if DNA[x] != 'C':
    Part2.append(DNA[x])
  x = x + 1
print("Part 2: ", Part2)

I removed that and unindented the increment.

You should consider using simpler code as has been posted already.

Seeing as you said you need to use a while loop...

dna = 'GTTGATGTAGCTTATATAAAGCAAGGCACTGAAAATGCCTAGATGAGTCATAGACTCCATAAACAACAGGTTTGGTCCCGGC'
x = 0
Part2 = []
while(x < len(dna)):
    if dna[x] != 'C':
        Part2.append(dna[x])
    else:
        pass
    x += 1

print("Part 2: ", Part2)

Alternatively, you can change Part2 to be a string, for the sake of readability at the end. I also removed the else: pass section as it isn't necessary to run the code.

dna = 'GTTGATGTAGCTTATATAAAGCAAGGCACTGAAAATGCCTAGATGAGTCATAGACTCCATAAACAACAGGTTTGGTCCCGGC'
x = 0
Part2 = ''
while(x < len(dna)):
    if dna[x] != 'C':
        Part2 += dna[x]
    x += 1

print("Part 2: ", Part2)

If you really need Part2 as a list, you can also use list() function. (or remove list() for string output as @Barmar and @Riccardo Bucco suggested)

DNA = 'GTTGATGTAGCTTATATAAAGCAAGGCACTGAAAATGCCTAGATGAGTCATAGACTCCATAAACAACAGGTTTGGTCCCGGC'
Part2 = list(DNA.replace('C', ''))
print("Part 2: ", Part2)
Related