【问题标题】:Insert substring if found如果找到则插入子字符串
【发布时间】:2012-11-28 20:27:47
【问题描述】:

我在 Python 中得到了一个字符串 my_str。我想要做的是:如果my_str 包含一个子字符串str1,则在子字符串str1 之后插入一个字符串str2(并保持my_str 的其余部分不变。)否则,什么也不做。 (假设my_str 包含的子字符串不超过一个str1。)

我的想法是:做一个for循环来查找str1是否存在于my_str

for i in range(0, len(my_str)-len(str1)):
  if my_str[i:i+len(str1)] == str1:
    my_str = my_str[0:i] + str2 + my_str[i:]

我很好奇是否有任何神奇的方法可以缩短这个时间。

【问题讨论】:

  • 不要命名变量strfiledictsetlist
  • @inspectorG4dget 谢谢,已编辑 :)

标签: python string


【解决方案1】:

最简单的方法是str.replace():

>>> str1 = "blah"
>>> str2 = "new"
>>> "testblah".replace(str1, str1+str2)
'testblahnew'
>>> "testblahtest".replace(str1, str1+str2)
'testblahnewtest'
>>> "test".replace(str1, str1+str2)
'test'
>>> "blahtestblah".replace(str1, str1+str2)
'blahnewtestblahnew'

我们只是用附加到自身的新字符串替换原始值,本质上是插入新值。

replace() 上的quick tutorial 获取更多示例。

【讨论】:

    【解决方案2】:
    def myReplace(myStr, str1, str2):
        try:
            i = myStr.index(str1)
            answer = myStr[:i+len(str1)] + str2 + myStr[i+len(str1):]
            return answer
        except ValueError:
            return myStr
    

    希望对你有帮助

    【讨论】:

    • 诚实的问题 - 这样做而不是使用内置的替换方法有什么好处?
    • @Anov:内置替换是我通常会使用的。由于 OP 似乎是初学者,我给出的答案更接近他试图实现的答案。我会在我的答案中使用 replace 的方式来完成此操作,但是当我完成编写此解决方案时,我注意到其他人已经发布了。
    • @inspectorG4dget 认为您使用 try-except 处理ValueError,如果是这种情况,则使用str.find(),如果未找到子字符串,则返回-1。
    • OP 的版本会将str1 的每个实例替换为str1+str2;你的只会取代第一个。 OP 说“假设 my_str 包含的子字符串不超过一个 str1”,但值得指出的区别。使用replace,您可以通过任何一种方式进行操作——将1 传递给count,或者不传递。您也可以通过添加一个循环并将i+1 作为start 传递给每个index/find 调用来使用此解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多