0

我是新来的,也是python,但我想试一试!我想在一个句子中用“top”替换“t”,用“hop”替换“h”,只有当“th”不可见时,因为“th”会变成“thop”。例如:“Thi hi tea”必须变成“thopi hopi topea”。我有这个代码:

sentence = str(raw_input('give me a sentence '))

start = 0
out = ''
while True:
    i = string.find( sentence, 'th', start )
    if i == -1:
        sentence = sentence.replace('t', 'top')
        sentence = sentence.replace('h', 'hop')
        break
    out = out + sentence[start:i] + 'thop'
    start = i+2

但不工作......有什么想法吗?

4

2 回答 2

6
import re

str = 'Thi hi tea'

re.sub(r'(?i)h|t(?!h)', r'\g<0>op', str)

产量

'Thopi hopi topea'

为了打破它,

  • import resub导入我们使用替换函数的正则表达式库
  • (?i)使正则表达式不区分大小写
  • t(?!h)匹配 't' 而不是后跟 'h'
  • \g<0>op是一个替换字符串,它替换原始文本,后跟"op".
于 2013-05-02T16:20:14.897 回答
0

这是功能:

>>>input : 'Thi hi tea'

>>>def function(string):
       string = string.lower()
       string = string.replace('t','top')   #replace all the 't' with 'top' from the string
       string = string.replace('h','hop')   # replace all the 'h' with 'hop'
       string =  string.replace('tophop','thop')   #where t and h will be together there i will get 'tophop', so i am replacing 'tophop' with 'thop'
       return string.capitalize() #for capitalize the first letter

回答: - - - - -

>>>function('Thi hi tea')
'Thopi hopi topea'

>>>function('Hi,who is there?')
'Hopi,whopo is thopere?'

谢谢

于 2013-05-02T18:05:42.440 回答