爲初學者蟒蛇,可能開始的最佳方法是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
re.sub可能會幫助... –
與其將數據存儲在字符串中,我建議將數據存儲在列表中。當你將它們打印出來時,你可以將它們結合在一起。與字符串不同,列表是* mutable *,這意味着您可以更改變量指向的**對象**。這樣,您可以創建一個函數,只在需要打印時將對象打印爲字符串* only *。 (如果你想打印每一個迭代,沒關係,如果你只想在最後打印,那也可以)。 – kreativitea