To loop through a sequence and terminate the loop once a condition isn't met, you can use break:
for char in string:
if char not in ('-', '+'):
break
do_something_with(char)
However, if you want to just collect those items matching the condition, you might be looking for itertools.takewhile:
def find_sign_prefix(s):
sign_prefix = list(itertools.takewhile(lambda char: char in ('-', '+'), s))
return sign_prefix
print find_sign_prefix("--+-++---3.141592+-+")
# '--+-++---'
Or specifically for examining a prefix of a string, you can use a regular expression:
def find_sign_prefix(s):
# `[+-]*` means "a '+' or '-' character, zero or more times";
# `re.search` only matches at the beginning of a string;
# group 0 is the matched substring
return re.search([+-]*, s).group(0)