2012-10-30 169 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'。