我想从下面的字符串_CD
中提取MUMBAI_SATARA_TIC_IND_MT_CD.xml
请找到下面给出的代码,但是,还有其他方法可以精确提取_CD
字吗?
text = 'MUMBAI_SATARA_TIC_IND_MT_CD.xml'
if "_CD" in text:
print("True")
预期输出:-
`_CD`
如何从上面的字符串中提取_CD
个单词?
答案 0 :(得分:-1)
import re
text = 'MUMBAI_SATARA_TIC_IND_MT_CD.xml'
text = re.compile('\w+').findall(text)[0]
text = text.split(text.split('_CD')[0])[1]
答案 1 :(得分:-1)
这无需使用正则表达式即可工作。
text = 'MUMBAI_SATARA_TIC_IND_MT_CD.xml'
if '_CD' in text:
ext_CD = text[text.find('_CD'):text.find('_CD')+3]
print(ext_CD)
## text.find('_CD'), gives you the staring index of the substring '_CD'
## text.find('_CD') + 3, gives you the ending index of the substring '_CD'
## with that, ext_cd = text[24:27]
Output:
_CD