有时需要多次调用提取字串内容的函数时,使用正则表达式不是很方便的时候,可以封装成函数调用。
get_int_after
def get_int_after(s, f):
S = s.upper()
F = f.upper()
par = S.partition(F)
int_str = ""
for c in par[2]:
if c in ("-", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"):
int_str += c
else:
if c == ":" or c == "=" or c == " ":
if int_str == "":
continue
break
try:
return int(int_str)
except:
print("Get Int After Fail")
print(f, s)
return "Parsing error"
例如: 获取如下字串中“Tput”的值:
string = "BLER0=7/100, BLER1=0/100, TRX=863 sf/s, Tput=29864840 bits/s, retx=8/100"
get_int_after(string, "Tput=")
#return 29864840
get_hex_after
def get_hex_after(s, f):
par = s.partition(f)
hex = 0
for c in par[2]:
cap_c = c.capitalize()
if ord(cap_c) in range(ord("0"), ord("9") + 1):
hex *= 16
hex += ord(cap_c) - ord("0")
elif ord(cap_c) in range(ord("A"), ord("F") + 1):
hex *= 16
hex += ord(cap_c) - ord("A") + 10
else:
if c == ":" or c == "=" or c == " " or c =="x":
if hex == 0:
continue
break
return hex
例如: 获取如下字串中“PSN”的值:
string = "Write to SIT: SIT(idx=0, pri=0), si_idx=[1232, 1246), PSN=0x8F71"
get_hex_after(string, "PSN=")
#return 0x8F71
get_str_btw
def get_str_btw(s, f, b):
par = s.partition(f)
return (par[2].partition(b))[0][:]
例如:获取如下字串中的“THIS IS WHAT YOU WANT”:
string = “123 THIS IS WHAT YOU WANT 456”
get_str_btw(string, "123 ", " 456") #注意空格
#return “THIS IS WHAT YOU WANT”