从字符串中提取部分

2024-09-30 02:21:32 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从字符串text1__text2_text3_text4_text5_text6中提取text1__text2_text3_text4_text5? 我尝试过这样的方法(这会给出我不感兴趣的text6),但无法得到正确的结果:

y = text1__text2_text3_text4_text5_text6
z = y.split('_')[6]

有人能帮忙吗(最好不用正则表达式)


Tags: 方法字符串splittext1text2text4text3text5
2条回答

您也可以尝试以下方法:

y = "text1__text2_text3_text4_text5_text6"
z = y.rsplit("_", 1)[0]

您正在访问位置,而不是访问直到位置

y = "text1__text2_text3_text4_text5_text6"
z = y.split('_')[:6]
print("_".join(z))    

相关问题 更多 >

    热门问题