如何在一定范围内递增字符串

2024-04-26 23:32:20 发布

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

我有一个像“F01”le code le“F16”这样的字符串,我想解析这个字符串,得到一个包含“F01”、“F02”、“F03”的新字符串。。。直到“F16”。你知道吗

我厌倦了用引号来解析字符串,希望能循环使用第一个代码直到最后一个代码。然后尝试通过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))

Tags: the字符串代码relerestforcode
1条回答
网友
1楼 · 发布于 2024-04-26 23:32:20

你就快到了。 从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"

相关问题 更多 >