我在想下面的...如果有更简单的方法可以帮助我,我需要为字母数字字符附加“T”
答案 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)