字符串替换python中的固定位置

时间:2013-10-20 16:37:50

标签: python string replace

我正在尝试做一个Trivia计划,而我正在回答问题。 我想要的是替换答案的字符作为提示显示。例如:

answer = "I am just an example"
hintwouldbe = "I a_ j___ a_ e______"
hint2mightbe = "I am j___ an e_a___e"

我不确定如何制作它。尝试使用循环(用于答案中的c)和string.replace方法。还尝试了一些re.translate和dicts,但我得到了非常大的代码,很难理解。必须是一个更方便的方式所以...我在这里。

您认为哪种方式最有效/更容易实现?

编辑如果我可以选择要替换的位置,那就太棒了。例如:如果单词有6个字符,则用_

替换1,3和6个字符

编辑2:正确答案

稍作修改之后,我选择Thomas Orozco的答案为有效,很容易理解并重新创作:

    from random import random
    answer = "anything in here"
    pista = [char if random() < 0.8 else "_" for char in answer]
    pista2 = "".join(pista)
    print(pista2)

4 个答案:

答案 0 :(得分:2)

字符串不适合您尝试做的事情,列表会做得更好。

import random

def make_hint(chars, frequency):
    hint_chars = [char if random.random() < frequency else "_" for char in chars]
    return "".join(hint_chars)

answer = "I am just an example"

print make_hint(answer, 0.3)
print make_hint(answer, 0.5)

当然,这只是一个例子。在这里,我使用随机显示30%或50%的字符,但您可以使用不同的实现。

请记住,在运行转换之前,您可以先回答问题.split()以将其拆分为单词:

print " ".join(make_hint(word, 0.3) for word in answer.split())

答案 1 :(得分:1)

你应该将你想到的逻辑(如你的例子,用6个字母的单词替换为1-st,3-r和6-th)放入结构(例如字典)中。然后,将句子分成单词并将逻辑应用于它们。 这是用_:

交换单词中所需位置的函数
def exchange(word,positions):
    chars=list(word)
        w=""
    for i in range(1,len(chars)+1):
        if i in positions:
            w+='_'
        else:
            w+=chars[i-1]
    return w

将逻辑放入字典中(7 - 用于捕捉'示例'一词,用4捕捉'只是'):

d={7:[1,3,6],4:[range(2,4+1)]}

最后应用逻辑:

words=answer.split() # split the sentence into word
' '.join(map(lambda x: exchange(x,d.get(len(x),[])),words)) # apply the logic and join results
>>> 'I am j___ an _x_mpl_'

答案 2 :(得分:1)

在指定位置替换字符:

answer = "I am just an example"   
''.join('_' if i in (1,3,6) else answer[i] for i in range(0, len(answer)))

为避免替换白色空格:

import string
answer = "I am just an example" 
def pr((c,i,L)):
 if (i in L and c in string.letters + string.digits):
  return '_'
 else:
  return c

''.join(map(pr,((answer[i],i,(1,3,6)) for i in range(len(answer)))))

并随机(假设您不想替换空格):

answer = "I am just an example"
import string
import random
''.join('_' if random.randint(0, 1) and i in string.letters + string.digits else i for i in answer)

答案 3 :(得分:0)

此方法自动将每个单词的第一个字母替换为“_”,然后允许基于索引的重新填充提示字母。它使用三个列表推导:

def hint(a, hidxs):
    return ''.join(c[i in idxs] for i, c in enumerate(a))

a = zip(' '.join(w[0] + '_'*(len(w)-1) for w in answer.split()), answer)
_idxs = [i for i, c in enumerate(hint(a, [])) if c == '_']

以下是如何使用它们:

>>> answer = "I am just an example"
>>> a = zip(' '.join(w[0 ]+ '_'*(len(w)-1) for w in answer.split()), answer)
>>> _idxs = [i for i, c in enumerate(hint(a, [])) if c == '_']
>>> _idxs #list of indexes for every '_'
[3, 6, 7, 8, 11, 14, 15, 16, 17, 18, 19]
>>> hidxs=[]
>>> print 'Hint 1:', hint(a, hidxs)
Hint 1: I a_ j___ a_ e______
>>> hidxs=[6]
>>> print 'Hint 2:', hint(a, hidxs)
Hint 2: I a_ ju__ a_ e______
>>> hidxs=[6, 14]
>>> print 'Hint 3:', hint(a, hidxs)
Hint 3: I a_ ju__ a_ ex_____
>>> hidxs=[6, 14, 17]
>>> print 'Hint 4:', hint(a, hidxs)
Hint 4: I a_ ju__ a_ ex__p__
>>> print 'Answer:', hint(a, _idxs)
Answer: I am just an example

随机提示的程序将是:

from random import shuffle
def hint(a, hidxs):
    return ''.join(c[i in idxs] for i, c in enumerate(a))

def all_hints(answer):
    a = zip(' '.join(w[0 ]+ '_'*(len(w)-1) for w in answer.split()), answer)
    _idxs = [i for i, c in enumerate(hint(a, [])) if c == '_']
    shuffle(_idxs)
    hints = []
    print 'Press enter for next hint:'
    for i in _idxs:
        print 'Hint:', hint(a, hints),
        hints.append(i)
        raw_input()
    print 'Answer:', hint(a, hints)