用空格替换字母

时间:2012-09-27 22:11:39

标签: python

我已经完成了这段代码,但我不能得到字母“t” - 小写和大写 - 用空格替换。我的代码的格式应该是相同的,但我只需要帮助用空格替换“t”。例如,“桌子上的书”应该看起来像“他能够预订的书”。所以,几乎应该隐藏“t”。

def remoeT(aStr):
    userInput = ""
    while True:
        string = raw_input("Enter a word/sentence you want to process:")
        if string == "Quit":
            return userInput

        userInput = userInput + string
        if aStr != False:
            while "t" in userInput:
                index = userInput.find("t")
                userInput = userInput[:index] + userInput[index+1:]
        while "T" in userInput:
            index = userInput.find("T")
            userInput = userInput[:index] + userInput[index+1:]

3 个答案:

答案 0 :(得分:5)

要使用字符串t中的空格替换所有出现的Tinput,请使用以下内容:

input = input.replace('t', ' ').replace('T', ' ')

或使用正则表达式:

import re
input = re.sub('[tT]', ' ', input)

答案 1 :(得分:4)

为什么不简单地使用replace功能?

s = 'The book on the table thttg it Tops! Truely'
s.replace('t', ' ').replace('T', ' ')

的产率:

' he book on  he  able  h  g i   ops!  ruely'

可能不如使用正则表达式那么好,但功能正常。

然而,这似乎比正则表达式方法快得多(感谢@JoranBeasley激励基准测试):

timeit -n 100000 re.sub('[tT]', ' ', s)
100000 loops, best of 3: 3.76 us per loop

timeit -n 100000 s.replace('t', ' ').replace('T', ' ')
100000 loops, best of 3: 546 ns per loop

答案 2 :(得分:3)

使用正则表达式:

>>> import re
>>> st = "this is a sample input with a capital T too."
>>> re.sub('[tT]', ' ', st)
' his is a sample inpu  wi h a capi al    oo.'

另外,不要将变量命名为“string”;有一个隐藏的“字符串”类。

相关问题