在Python2.7中,只有当“th”不是visib时,如何用“top”替换“t”,用“hop”替换“h”

2024-09-27 09:36:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来这里和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

但不起作用…有什么想法吗?你知道吗


Tags: tophioutstartsentencereplace句子th
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)使regex大小写不敏感
  • t(?!h)匹配“t”而不是后跟“h”
  • \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?'

谢谢

相关问题 更多 >

    热门问题