我有一个字符串,例如'“ F01” le code le“ F16”'我想解析该字符串以获取一个新字符串,其中包含“ F01”,“ F02,” F03“ ...直到” F16“。 / p>
我厌倦了用引号来解析字符串,希望循环遍历第一个代码直到最后一个代码。然后尝试通过chr()和ord()递增代码。但是似乎无法弄清楚。
import re
s = '"F01" le code le "F16"'
s_q = re.findall('"([^"]*)"', s)
first_code = s_q[0]
last_code = s_q[1]
ch_for_increment = s_q[0][-1:]
ch_for_the_rest = s_q[0][:-1]
print(ch_for_the_rest + chr(ord(ch) + 1))
答案 0 :(得分:2)
您快到了。
从s_q
中提取范围的开始和结束之后,您可以像这样使用range来生成列表。
import re
s = '"F01" le code le "F16"'
s_q = re.findall('"([^"]*)"', s)
#['F01', 'F16']
#Extract the first and last index of range from list
first_code = int(s_q[0][1:])
#1
last_code = int(s_q[1][1:])
#16
#Create the result list
li = ['F{:02d}'.format(item) for item in range(first_code, last_code+1)]
#Get the final string with quotes
result = '"{}"'.format('" "'.join(li))
print(result)
输出将为
"F01" "F02" "F03" "F04" "F05" "F06" "F07" "F08" "F09" "F10" "F11" "F12" "F13" "F14" "F15" "F16"