【问题标题】:string splitting with multiple values using re.split()使用 re.split() 拆分多个值的字符串
【发布时间】:2020-05-03 14:59:51
【问题描述】:

我有一个字符串: "2y20w2d2h2m2s" 我需要将其拆分为: ["2y","20w","2d","2h","2m"2s”] 我尝试使用 re.split 但我无法让它工作 这是我的尝试: time = re.split("s m h d w y", time) *time 是上面的字符串 最后,我将帮助您了解如何使其工作

【问题讨论】:

  • 您希望字符串分割成的部分是否总是以 2 开头?
  • 一个很好的 Q 我忘了 sepcify 但它不应该只有 2 它应该是任何数字

标签: python python-3.x list split python-re


【解决方案1】:

代码:

import re

time_str = "2y20w2d2h2m2s"
time = re.findall(r"(\d*\S)", time_str)
print(time)

输出:

>>> python3 test.py 
['2y', '20w', '2d', '2h', '2m', '2s']

在线试用:

【讨论】:

    【解决方案2】:

    如果您希望将字符串拆分成的部分始终以 2 开头,则可以这样做:

    string = "2y20w2d2h2m2s"
    
    print(string.replace('2', ' 2').split())
    

    【讨论】:

      【解决方案3】:

      试试:

      import re
      
      print(re.findall('(\d+[a-z])', "2y20w2d2h2m2s"))
      

      输出

      ['2y', '20w', '2d', '2h', '2m', '2s']
      

      说明

      1 个或多个数字后跟一个字母的正则表达式模式

      (\d+[a-z])
      

      【讨论】:

        【解决方案4】:

        尽可能具体地针对您的用例:

        import re
        s = "2y20w2d2h2m2s"
        re.findall('([0-9]{1,2}[ywdhms]{1})', s)
        

        输出:['2y', '20w', '2d', '2h', '2m', '2s']

        这会产生您想要的结果,没有多余的字母或超过两位数的数字。

        【讨论】:

          猜你喜欢
          • 2022-11-23
          • 1970-01-01
          • 2014-07-18
          • 1970-01-01
          • 2013-01-15
          • 1970-01-01
          • 2019-07-19
          • 1970-01-01
          • 2018-02-27
          相关资源
          最近更新 更多