我需要确保用户放入函数的字符串只包含字母“A”,“T”,“G”和“C”。如果它包含任何其他字符,我需要能够返回错误消息。例如:如果用户输入“ATTGACT”,字符串将通过我的函数前进,但如果用户输入“ATTQWSCT”,该字符串将触发错误消息。这是针对涉及DNA的函数,因此字符串只能包含这些字母。
答案 0 :(得分:4)
使用re
非常容易:
import re
pattern = "[^ACTG]+"
string = raw_input()
if re.findall(pattern, string):
#error
else:
#your code here
...或默认的Python集:
string = raw_input()
if set(string) <= {"A", "C", "T", "G"}:
#error
else:
#your code here
...或迭代:
string = raw_input()
for i in string:
if not (i in "ACTG"):
#error
# Or, as @l4mpi said:
all(c in "ACTG" for c in string)
答案 1 :(得分:0)
sequence="AATQWIC"
correct = "ATGC"
for each_char in sequence:
if not each_char in correct:
print "Error"