0

I have a string like '"F01" le code le "F16"' I want to parse this string to get a new string contains "F01", "F02, "F03" ... until "F16".

I tired to parse the string by quotes and hope to loop through the first code till the last code. And then tried to increment the code via chr() and ord(). But can't seem to figure it out.

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))
2
  • What is the string you are looking for @GuZhao ? F01 F02 F03 F04 F05 F06 F07 F08 F09 F10 F11 F12 F13 F14 F15 F16 or "F01" "F02" "F03" "F04" "F05" "F06" "F07" "F08" "F09" "F10" "F11" "F12" "F13" "F14" "F15" "F16" Commented May 27, 2019 at 6:39
  • Thanks so much. Was looking for the latter one with quotes Commented May 27, 2019 at 6:45

1 Answer 1

2

You are almost there. After extracting the start and end of range from s_q, you can use range to generate your list like so.

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)

The output will be

"F01" "F02" "F03" "F04" "F05" "F06" "F07" "F08" "F09" "F10" "F11" "F12" "F13" "F14" "F15" "F16"
Sign up to request clarification or add additional context in comments.

1 Comment

OP wanted a string, so print(*result) will help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.