如何删除两个子字符串之间的字符串中的所有文本。Python 2.7

2024-10-03 06:30:09 发布

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

我需要一个函数,它将遍历一个字符串并删除两个字符串"About DoctorTardi""Stats for Project Ares"之间的所有内容。在

答案可能就在我面前。。在


Tags: 函数字符串答案project内容forstatsabout
3条回答
x = "About DoctorTardi bla bla Stats for Project Ares"
x = x[:17]+x[25:]
print x

将打印

About DoctorTardi Stats for Project Ares

  • x[:17]是x的子字符串,从开始到第17个字母。

  • x[25:]是x的子字符串,从第25个字母到结尾。

  • x[17:25]是x的子字符串,从17个字母到25个字母 信。

使用^{}^{}

>>> s = "aaa About DoctorTardi this Stats for Project Ares bbb"
>>> head, sep1, x = s.partition("About DoctorTardi")
>>> _, sep2, tail = x.partition("Stats for Project Ares")
>>> head + sep1 + sep2 + tail
'aaa About DoctorTardiStats for Project Ares bbb'
   def remake_string(initialString, startPhrase, endPhrase):

       startingIndex = initialString.rfind(startPhrase)e #finds the highest index of the phrase
       endingIndex = initialString.find(endPhrase)# finds the lowest index of the phrase
       newString = initialString[:startingIndex] + initialString[endingIndex:] ''' 
       removes everything in the midding by starting getting everything up to the end of 
       the startPhrase and adding it to from the endPhrase on '''

       return newString

相关问题 更多 >