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

我正在考虑以下内容......如果有更简单的方法可以实现这一点,任何人都可以帮助我,我需要为字母数字字符附加“T”

  1. 基于“。”的拆分
  2. 一旦遇到第一个数字(在本例中为“120108A”),获取 `split[0]` 的字母数字字符
  3. 将“T”附加到#2(它将是 120108AT)
  4. 然后放回`split[1]`(120108AT.1)
4

1 回答 1

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)
于 2012-12-12T03:43:52.567 回答