作为 python 的初学者,最好的开始方法可能是将您的要求 1:1 映射到您的代码 - 我希望以下内容尽可能不言自明:
def generate_next_fmla (complete_fmla, partial_fmla, symbol):
# test that complete_fmla does not contain '-'
if '-' in complete_fmla:
raise ValueError("comple_fmla contains '-'")
# delete all spaces from partial_fmla if needed (this need was suggested
# in the original question with some examples that contained spaces)
partial_fmla = partial_fmla.replace(' ', '')
# test if it is possible to test the "same positions" from both strings
if len(complete_fmla) != len(partial_fmla):
raise ValueError("complete_fmla does not have the same lenght as partial_fmla")
# add other input checking as needed ...
if symbol not in complete_fmla or symbol in partial_fmla:
return partial_fmla
# partial_fmla[i] = symbol wouldn't work in python
# because strings are immutable, but it is possible to do this:
# partial_fmla = partial_fmla[:i] + symbol + partial_fmla[i+1:]
# and another approach is to start with an empty string
result = ''
for i in range(len(partial_fmla)):
# for every character position in the formulas
# if there is '-' in this position in the partial formula
# and the symbol in this position in the complete formula
if partial_fmla[i] == '-' and complete_fmla[i] == symbol:
# then append the symbol to the result
result += symbol
else:
# otherwise use the character from this positon in the partial formula
result += partial_fmla[i]
return result
print(generate_next_fmla ('abcdeeaa', '--------', 'd')) # ‘---d----’
print(generate_next_fmla ('abcdeeaa', '- - - x - - - - ', 'e')) # ‘---xee--’
print(generate_next_fmla ('abcdeeaa', 'x-------', 'a')) # ‘x-----aa’
print(generate_next_fmla ('abcdeeaa', 'x-----', 'a')) # Exception