简体   繁体   中英

Check for invalid character

Hello i am trying to figure out the following:

Write the code to check whether a string given throughinput()contains only valid characters, but stop once you reach one invalid character. Do not forget that will print a little bit differently now, we want to see the valid part of the string too.

Sample Input: ATCGT ( but it can be other inputs)

Sample Output: valid ATCGT

file = input()


for current_letter in file:
    if current_letter in ['A', 'T', 'G', 'C']:
        continue
    elif current_letter not in ['A', 'T', 'G', 'C']:
        break
print ('valid '+current_letter)

But my output is only : valid T

EDIT:

file = input()

correct_letters = []

for current_letter in file:
    if current_letter in ['A', 'T', 'G', 'C']:
        correct_letters.append(current_letter)
    else:
        break
print(f'valid {"".join(correct_letters)}')

This works also fine, thanks to L3viathan

You're not doing what the instructions tell you. Here you give the last correct letter. This will do the trick:

file = input()
correct_letters = ""
for current_letter in file:
    if current_letter in ['A', 'T', 'G', 'C']:
        correct_letters += current_letter
    else:
        break
print ('valid  '+ correct_letters)

I think you should be able to just always print valid , and then print characters one at a time, until you find a "bad" letter:

file = input()

print("valid ", end="")
for current_letter in file:
    if current_letter in ['A', 'T', 'G', 'C']:
        print(current_letter, end="")
    else:
        break
print("")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM