拆分并追加

时间:2012-12-12 03:36:27

标签: python

  • 输入: - A89456FRERT120108A.1
  • 预期产出: - 120108AT.1

我在想下面的...如果有更简单的方法可以帮助我,我需要为字母数字字符附加“T”

  1. 根据“。”拆分
  2. 遇到第一个数字后获取“split [0]”的字母数字字符(在这种情况下为“120108A”)
  3. 将“T”追加到#2(它将是120108AT)
  4. 然后放回`split [1]`(120108AT.1)

1 个答案:

答案 0 :(得分:4)

这是一个正则表达式解决方案,它尝试使用您提供的相同逻辑:

import re
new_string = re.sub(r'^.*?(\d+\D*)(\..*)', r'\1T\2', orig_string)

示例:

>>> re.sub(r'^.*?(\d+\D*)(\..*)', r'\1T\2', 'A89456FRERT120108A.1')
'120108AT.1'

说明:

#regex:
    ^            # match at the start of the string
    .*?          # match any number of any character (as few as possible)
    (            # start capture group 1
      \d+          # match one or more digits
      \D*          # match any number of non-digits
    )            # end capture group 1
    (            # start capture group 2
      \..*         # match a '.', then match to the end of the string
    )            # end capture group 2

#replacement
    \1           # contents of first capture group (from digits up to the '.')
    T            # literal 'T'
    \2           # contents of second capture group ('.' to end of string)