根据输入列表将字符串解析为列表

时间:2017-04-27 15:21:13

标签: python python-2.7 python-3.x

我想在python3中编写一个函数来根据输入列表元素解析字符串。以下功能有效但是有更好的方法吗?

def func(oStr, s_s):
    if not oStr:
        return s_s
    elif '' in s_s:
        return [oStr]
    else:
        for x in s_s:
            st = oStr.find(x)
            end = st + len(x)
            res.append(oStr[st:end])
            oStr = oStr.replace(x, '')
        if oStr:
            res.append(oStr)
        return res

案例1

o_str = 'ABCNew York - Address'
s_str = ['ABC']
return ['ABC', 'New York - Address']

案例2

o_str = 'New York Friend Add |  NumberABCNewYork Name  | FirstName Last Name | time : Jan-31-2017'
s_str = ['New York Friend Add |  Number', 'ABC', 'NewYork Name  | FirstName Last Name | time: Jan-31-2017']
return ['New York Friend Add |  Number', 'ABC', 'NewYork Name  | FirstName Last Name | time: Jan-31-2017']

案例3

o_str = '-'
s_str = ['']
return ['-']

案例4

o_str = '1'
s_str = ['']
return ['1']

案例5

o_str = '1234Family-Name'
s_str = ['1234']
return ['1234', 'Family-Name']

案例6

o_str = ''
s_str = ['12345667', 'name']
return ['12345667', 'name']

1 个答案:

答案 0 :(得分:0)

要使用类似于数组的字符串,您只需以相同的方式对其进行编程。例如

myStr="Hello, World!"
myString.insert(len(myString),"""Your character here""")

出于您的目的,.append()的工作方式完全相同。希望我帮忙。