我是新来的,也是python,但我想试一试!我想把一个句子中的"t"换成"top","h"换成"hop",只有当"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
但不工作…什么好主意吗?
import re
str = 'Thi hi tea'
re.sub(r'(?i)h|t(?!h)', r'g<0>op', str)
收益率'Thopi hopi topea'
-
import re
导入正则表达式库,我们从中使用替换sub
,函数 -
(?i)
使正则表达式不区分大小写 -
t(?!h)
匹配不后跟'h'的't' -
g<0>op
是一个替换字符串,用来替换原文本后面跟着"op"
。
函数如下:
>>>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?'
谢谢