首页 > 解决方案 > 如何用输入字符串中的相应字符串切片替换所有“&int-int”?

问题描述

我有一个学校项目问题(针对 Python),如下所示:

给定一个字符串输入,例如“abcd&1-4efg”,该函数必须删除“&1-4”并在“&1-4”所在的位置插入从1到4的字符串切片。

例如。如果 string_input = "abcd&1-4efg",

  1. “&1-4”被删除。

  2. 其余字符索引如下:a=0, b=1, c=2, d=3, e=4, f=5, g=6

  3. 新字符串变为:“abcdbcdeefg”

我已经设法编写了一大段代码来做到这一点,但我想知道是否有人有更有效的解决方案?

注意事项:

  1. 指令可以包含两位数(例如 &10-15)
  2. 如果未找到索引,则返回的字符串应打印“?” 对于每个缺失的索引(例如,“abcd&5-10efgh”将返回“abcdfgh???efgh”)
  3. 指令可以是背靠背的(例如“&10-15abcdef&1-5&4-5pqrs”)

我写的代码是:

def expand(text):
text += "|"
import string
digits_dash = string.digits + "-"

idx_ref_str = ""
replace_list = []
record_val = False
output_to_list = []
instruct = ""
and_idx_mark = 0

#builds replace_list & idx_ref_list
for idx in range(len(text)):
    if text[idx] == "&" and record_val==True:
        output_to_list.append(instruct)
        output_to_list.append(and_idx_mark)
        replace_list.append(output_to_list)
        output_to_list, instruct, inst_idx, and_idx_mark = [],"",0,0

        and_idx_mark = idx
        continue
    elif text[idx] == "&":
        record_val = True
        and_idx_mark = idx
        continue

    #executes if currently in instruction part
    if record_val == True:
        #adds to instruct
        if text[idx] in digits_dash:
            instruct += text[idx]
        #take info, add to replace list
        else:
            output_to_list.append(instruct)
            output_to_list.append(and_idx_mark)
            replace_list.append(output_to_list)
            output_to_list, instruct, inst_idx, and_idx_mark, record_val = [],"",0,0,False

    #executes otherwise
    if record_val == False:
        idx_ref_str += text[idx]

idx_ref_str = idx_ref_str[:-1]
text = text[:-1]

#converts str to int indexes in replace list[x][2]
for item in replace_list:
    start_idx = ""
    end_idx = ""
    #find start idx
    for char in item[0]:
        if char in string.digits:
            start_idx += char
        elif char == "-":
            start_idx = int(start_idx)
            break
    #find end idx
    for char in item[0][::-1]:
        if char in string.digits:
            end_idx = char + end_idx
        elif char == "-":
            end_idx = int(end_idx)
            break

    start_end_list = [start_idx,end_idx]
    item+=start_end_list

#split text into parts in list
count = 0
text_block = ""
text_block_list = []

idx_replace = 0

for char in text:
    if char == "&":
        text_block_list.append(text_block)
        text_block = ""
        count += len(replace_list[idx_replace][0])
        idx_replace +=1
    elif count > 0:
        count -= 1
    else:
        text_block += char

text_block_list.append(text_block)

#creates output str
output_str = ""

for idx in range(len(text_block_list)-1):
    output_str += text_block_list[idx]

    #creates to_add var to add to output_str
    start_repl = replace_list[idx][1]
    end_repl = replace_list[idx][1] + len(replace_list[idx][0])

    find_start = replace_list[idx][2]
    find_end = replace_list[idx][3]

    if end_idx >= len(idx_ref_str):
        gap = end_idx + 1 - len(idx_ref_str)
        to_add = idx_ref_str[find_start:] + "?" * gap
    else:
        to_add = idx_ref_str[find_start:find_end+1]
    
    output_str += to_add

output_str += text_block_list[-1]

return output_str

标签: pythonpython-3.x

解决方案


这就是我将如何做到的。总是对批评持开放态度。

import re

s = 'abcd&1-4efg'

c = re.compile('&[0-9]+-[0-9]+')

if (m := c.search(s)):
    a, b = m.span()
    left = s[:a]
    right = s[b:]
    o = [int(x) for x in m.group(0)[1:].split('-')]
    mid = (left+right)[o[0]:o[1]+1]
    print(left + mid + right)

推荐阅读