Python 拆分和追加 输入:-A89456FRERT120108A.1 预期输出:-120108AT.1
我在想下面的问题…有谁能帮我吗?如果有更简单的方法来实现这一点,我需要为字母数字字符添加T 基于。 在遇到第一个数字(本例中为120108A)后,获取“拆分[0]”的字母数字字符 将T附加到2,它将是120108AT 然后放回'split[1]'120108AT.1Python 拆分和追加 输入:-A89456FRERT120108A.1 预期输出:-120108AT.1,python,Python,我在想下面的问题…有谁能帮我吗?如果有更简单的方法来实现这一点,我需要为字母数字字符添加T 基于。 在遇到第一个数字(本例中为120108A)后,获取“拆分[0]”的字母数字字符 将T附加到2,它将是120108AT 然后放回'split[1]'120108AT.1 下面是一个regex解决方案,它尝试使用您提供的相同逻辑: import re new_string = re.sub(r'^.*?(\d+\D*)(\..*)', r'\1T\2', orig_string) 例如: >&
下面是一个regex解决方案,它尝试使用您提供的相同逻辑:
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)
下面是一个regex解决方案,它尝试使用您提供的相同逻辑:
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)
这可能是正则表达式的情况。这可能是正则表达式的情况。