从子字符串开始获取长度有限的子字符串

时间:2019-10-18 09:49:59

标签: python python-2.7

我知道如何使用索引从字符串中获取子字符串,但是我想要一个从子字符串开始且长度有限的子字符串。

例如。我有字符串:

7F4P_gmLYIQottr9LMsJ5_arena_word2_fdsfds_fdsfds_fgdgdfs

我想要一个从字词arena开始的子字符串,但不能超过40个字符。结果应该是:

arena_word2_fdsfds_fdsfd

下划线“ _”是随机生成的,因此我不能仅在第二个下划线之后进行分割。

1 个答案:

答案 0 :(得分:2)

word = "7F4P_gmLYIQottr9LMsJ5_arena_word2_fdsfds_fdsfds_fgdgdfs"

result = "arena" + word.split("arena")[-1] #append the word "arena" and the characters after the word "arena"

limit_result = result[:40] #limit the result to 40 characters

最终结果:“ arena_word2_fdsfds_fdsfds_fgdgdfs”