2012-10-30 167 views
0

我對python非常陌生。有人可以解釋我如何操縱這樣的字符串嗎?如何替換部分字符串?

該函數接收三個輸入:

  • complete_fmla:具有數字和符號的字符串,但沒有連字符('-'),也不空格。
  • partial_fmla:具有連字符和可能的一些數字或符號,其中是在它的數字和符號(比連字符等)都在相同的位置在complete_formula的組合。
  • 符號:一個字符

輸出應返回是:

  • 如果該符號不是完整的配方中,或者如果符號已經部分式中,該函數應該返回與輸入partial_formula相同的公式。
  • 如果符號位於complete_formula而不是部分公式中,則函數應該返回partial_formula,其中符號將替換符號所在位置中的連字符,即complete_formula中符號的所有出現。

基本上,我與定義的工作:

def generate_next_fmla (complete_fmla, partial_fmla, symbol): 

不要我把它們變成列表?然後追加? 此外,我是否應該找出complete_fmla中符號的索引號,以便我知道在帶連字符的字符串中將它附加到哪裏?

+1

re.sub可能會幫助... –

+0

與其將數據存儲在字符串中,我建議將數據存儲在列表中。當你將它們打印出來時,你可以將它們結合在一起。與字符串不同,列表是* mutable *,這意味着您可以更改變量指向的**對象**。這樣,您可以創建一個函數,只在需要打印時將對象打印爲字符串* only *。 (如果你想打印每一個迭代,沒關係,如果你只想在最後打印,那也可以)。 – kreativitea

回答

0

問候,你可以嘗試使用正則表達式,我想他們會幫助你很多你想要達到的目標,在這裏你有一個文檔內link

一些exemples:

>>> import re 
>>> m = re.search('(?<=abc)def', 'abcdef') 
>>> m.group(0) 
'def' 
1

這是一個簡單的onliner功能

def generate_next_fmla(base, filt, char): 
    return ''.join(c if c==char else filt[idx] for idx,c in enumerate(base) ) 

的核心思想是,如果其他條款:

c if c==char else filt[idx] 

其中,給定的每個字符和它在原始字符串的位置,把它在新的字符串,如果等於所選擇的字符,otherway地方從過濾字符串

的值寫在一個更冗長的方式,如下所示:

def generate_next_fmla (complete_fmla, partial_fmla, symbol): 
    chars = "" 
    for idx in range(len(complete_fmla)): 
     c = complete_fmla[idx] 
     if c==symbol: 
      chars = chars + c 
     else: 
      chars = chars + partial_fmla[idx] 
    return chars 

這是寫在一個更上幾行(它實際上是方式效率較低,因爲字符串的太陽是一個不好的習慣)

+0

'complete_fmla'(base)和'partial_fmla'(filt)在問題中似乎沒有相同的長度 - 「filt [idx * 2]」應該覆蓋2倍於基準長度的情況... – Aprillion

+0

Weel ,實際上他指定了partial_fmla列表中的字符與原始字符位於相同的位置。鑑於額外的空間和奇怪的字符串分隔符,它似乎是從練習中複製的,不是嗎? :( – EnricoGiampieri

+0

哦,我編輯了有問題的示例以符合此規範(在OP之前刪除示例:() – Aprillion

0

相同功能無懷疑有e DGE情況下,你將需要添加,但是這應該很簡單情況下工作:

def generate_next_fmla (complete_fmla, partial_fmla, symbol): 
    result = partial_fmla.strip().split(' ')[:] 
    for index, c in enumerate(complete_fmla): 
     if c == symbol: 
      result[index] = c 
    return "".join(result) 

它轉換成一個列表,然後再返回,使更換更容易。

編輯:我現在意識到這是類似於EnricoGiampieri的答案,但與列表。

0

爲初學者蟒蛇,可能開始的最佳方法是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 
0

您可以檢查此代碼:

lst_fmla = [] 
def generate_next_fmla(s_str, fmla, c_char): 
    i = 0 
    for s in s_str: 
     if c_char is s: lst_fmla.append(c_char) 
     elif fmla[i] != '-': lst_fmla.append(fmla[i]) 
     else: lst_fmla.append('-') 
     i = i + 1 
    print(''.join(lst_fmla)) 
generate_next_fmla('abcdeeaa', '---d----', 'e') 

如果例如您在函數generate_next_fmla第二個參數是這樣「---- d ---」,其「d」。將第三個參數(「E」的相同的索引),它將被替換爲'e'。