首页 > 解决方案 > 从python中指定的字符串中获取n个字符

问题描述

让 s = "%2ABCDE" - 从字符串中获取前 2 个字符,然后输出应该是 "AB"。需要从字符串中由数字指定的字符串中获取字符。例如 s1="%12ABCDERTYUIOPLKHGF" - 从字符串中获取前 12 个字符。

我尝试使用 re.findall('\d+', string ) 获取数字,但如果我的字符串为“%2ABCD1”,则会出现问题。请建议

标签: pythonpython-3.xstring

解决方案


s = "%2ABCDE"
number = ""
offset = 0
for i in range(len(s)):
    if s[i] == "%":
        continue
    elif s[i].isdigit():
        number += s[i]
    else:
        offset = i
        break

print(s[offset:int(number) + offset])

输出:AB


推荐阅读