删除字符串中的字符,用包含原始字符的列表中的不同字符替换

时间:2013-07-08 21:13:37

标签: python

from random import randint

def replace_base_randomly_using_names(base_seq):
    """Return a sequence with the base at a randomly selected position of base_seq
    replaced by a base chosen randomly from the three bases that are not at that
    position."""
    position = randint(0, len(base_seq) - 1) # −1 because len is one past end
    base = base_seq[position]
    bases = 'TCAG'
    bases.replace(base, '') # replace with empty string!
    newbase = bases[randint(0,2)]
    beginning = base_seq[0:position] # up to position
    end = base_seq[position+1:] # omitting the base at position
    return beginning + newbase + end

这应该模拟一个突变。我不明白如何选择不同的基础(来自TCAG内部)以确保基础确实改变,正如doctype所提到的那样。

编辑:

上述代码的另一个版本执行相同的操作:

def replace_base_randomly(base_seq):
    position = randint(0, len(base_seq) - 1)
    bases = 'TCAG'.replace(base_seq[position], '')
    return (base_seq[0:position] +
            bases [randint(0,2)] +
            base_seq[position+1:])

要明确的是,我的问题是如何用不同的基础替换基础?

3 个答案:

答案 0 :(得分:1)

考虑将print语句交错到代码中,你可以看到它正在做什么。这是算法:

  • 在字符串中选择随机索引。将其保存为“位置”。
  • 将该索引处的字符保存为“base”。
  • 在“TCAG”列表中,将字符“base”替换为空字符串,并将该列表保存为“bases”(因此它将包含不是索引“position”处的每个基数)。
  • 从“bases”中选择一个随机字符,并将该字符另存为“newbase”。 (因此,在移除您最初随机挑选的基地后,它将成为剩下的三个基地之一。)
  • 返回三个字符串的串联:原始字符串,但不包括“position”,“newbase”和原始字符串,但不包括“newbase”。

它不会编辑字符串 - 它会从旧字符串的两个部分再加上新的字符串创建一个新字符串,然后返回该字符串。

答案 1 :(得分:0)

字符串在python中是不可变的,您应该将从bases.replace(base, '')返回的字符串重新分配给bases

bases = bases.replace(base, '')

答案 2 :(得分:0)

bases.replace(base, '')实际上并未更改bases字符串。要更改bases字符串,您必须设置bases = bases.replace(base, '')。自己测试

bases = 'ACGT'
base = 'A'
print bases #prints 'ACGT'
bases.replace(base, '')
print bases #prints 'ACGT'
bases = bases.replace(base, '')
print bases #prints 'CGT'

从这里开始,现在可能的碱基列表已经减少到只有突变的碱基,该函数随机选择一个带bases[randint(0, 2)]的碱基并将其附加到新序列。