【问题标题】:How to split string in Python to take only middle characters?如何在 Python 中拆分字符串以仅使用中间字符?
【发布时间】:2020-11-03 20:40:02
【问题描述】:

我有字符串

['tick_calculated_2_2020-05-27T11-59-06.json.gz']

我只想得到59-06

>>> f.split('_')
['tick', 'calculated', '2', '2020-05-27T11-59-06.json.gz']
>>> f.split('_')[3]
'2020-05-27T11-59-06.json.gz'

>>> f.split('_')[3].split('.')[0]
'2020-05-27T11-59-06'

下一步应该做什么?

【问题讨论】:

    标签: python string split slice


    【解决方案1】:

    这使用 Positive lookahead 和 Positive lookbehind 来断言匹配准确发生。

    import re
    
    string = 'tick_calculated_2_2020-05-27T11-59-06.json.gz'
    
    re.search(r'(?<=T\d{2}-)\d{2}-\d{2}(?=\.json)', string).group()
    

    输出:

    59-06
    

    【讨论】:

      【解决方案2】:

      你正朝着正确的方向前进。
      与其他答案相反,我觉得正则表达式有点矫枉过正,除了更慢更难理解和维护。

      获得字符串x = '2020-05-27T11-59-06' 后,您可以执行x.split('-') 来获取列表lst = ['2020', '05', '27T11', '59', '06']
      然后,您可以访问此列表的最后 2 个元素以轻松获得所需内容:lst[-1], lst[-2]

      【讨论】:

        【解决方案3】:

        你可以这样使用str.rfind

        index = s.rfind('-')
        s[index - 2:index + 3]
        

        或者这样使用正则表达式:

        import re
        re.search(r'.{5}(?=\.json)', s).group()
        

        【讨论】:

          【解决方案4】:

          假设您不知道使用正则表达式,请尝试 Google python 字符串切片。你有正确的想法用“_”分割,继续用“。”分割。然后对最后 5 个字符获取的字符串进行切片

          f = 'tick_calculated_2_2020-05-27T11-59-06.json.gz'
          splitted = f.split('_')
          print(splitted)
          
          date = splitted[3].split('.')[0]
          specialNum = date[-5:]
          print(specialNum)
          

          【讨论】:

            【解决方案5】:

            您可以尝试使用re(正则表达式)。

            import re
            
            f = "tick_calculated_2_2020-05-27T11-59-06.json.gz"
            
            res = re.search(r"T\d+\-([\d\-]+)\.json\.gz", f)
            
            print(res.groups()[0])
            

            输出: 59-06

            【讨论】:

              猜你喜欢
              • 2016-11-09
              • 2013-06-27
              • 2023-03-21
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-12-17
              相关资源
              最近更新 更多