【问题标题】:splitting a string if a substring has occured如果出现子字符串,则拆分字符串
【发布时间】:2015-10-29 22:11:18
【问题描述】:

我怎么能说如果一个字符串命中 https(没有空格)将它分成两个单词? 例如在Join us!https://t.co/Fe0oTahdom 想要使其像Join us!https://t.co/Fe0oTahdom

【问题讨论】:

    标签: python string split


    【解决方案1】:

    如果您只打算在 https 关键字上进行拆分,最简单的方法

    myString = 'Join us!https://t.co/Fe0oTahdom'
    
    (head, sep, tail) = myString.partition('https')
    
    print head  #Prints Join us!
    print sep + tail #Prints the rest
    

    【讨论】:

      【解决方案2】:

      阅读index

      s = 'Join us!https://t.co/Fe0oTahdom'
      [s[0:s.index('https')], s[s.index('https'):]]
      

      【讨论】:

        【解决方案3】:

        您可以使用index 方法找到https

        s = 'Join us!https://t.co/Fe0oTahdom'
        idx = s.index('https')
        parts = [s[0:idx], s[idx:]]
        

        【讨论】:

          【解决方案4】:

          没有正则表达式的解决方案是不完整的!

          import re
          
          s = 'join us!https://t.co/Fe0oTahdom'
          tokens = re.split('(https)', s)
          print tokens[0]
          print tokens[1] + tokens[2]
          

          【讨论】:

          • 如果网址恰好包含“https”,例如s = 'join us!https://t.co/Fehttpsom',则此答案存在缺陷。这种类型的错误是最令人沮丧的问题之一。
          【解决方案5】:

          如果 https 在字符串中,则拆分并加入。

          string = "Join us!https://t.co/Fehttpsom"
          if "https://" in string:
              print " https://".join(string.split("https://", 1))
          

          加入我们! https://t.co/Fehttpsom 并确保您不会仅在第一次出现 https 时拆分,如“立即使用 https 访问我们的网站;)”

          【讨论】:

          • 这与@MK.的回答有同样的问题。不过,您可以将 1 传递给 maxsplit 参数。
          • @JohnLaRooy 你是对的,我学到了一些东西 - winwin ;)
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-10-24
          • 2014-10-12
          • 1970-01-01
          • 2016-04-28
          • 2019-10-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多