Multifunctional function code design using Python to split a string into multiple substrings

Python method to split a string into multiple substrings

To split a Python string into multiple substrings, you can use the split() method of the string object. However, when using the method, you need to pay attention to the passing of parameters. To be precise, you need to observe the characteristics of the original string, such as whether there are the same delimiters between the target substrings. Therefore, the use of this method can be divided into Two situations. Now listed below:

  • There are the same separators between substrings. For example, the three substrings "A", "B" and "C" in the string "A, B, C" are separated by ",", then you can Pass the "," characters as parameters to the split() method to split the Python string into multiple target substrings at one time;
  • There are no same delimiters between substrings, such as "C, D, E", then you need to use the split() method multiple times to split the string to get the target substring;

Python function design to split a string into multiple substrings

We should design a function that can split the string at once when the same delimiter is present, or split the string when the same delimiter does not exist. Therefore, we need to pass a parameter as information to tell the function Whether the programs have the same delimiter, and then execute different programs according to different situations. In addition, we also need a variable parameter to pass different separators to the split() method multiple times. Another point is that the return value of the split() method is a list. We will access the elements of the list through indexing in the order of the passed separator. For details, please refer to the code below:

def splitStr(strObj, seq=True, *seqList):
    if seq:
        strList = strObj.split(seqList[0])
    else:
        strList = []
        strObjList = [strObj]
        for i in range(len(seqList)):

            strObjList = strObjList[0].split(seqList[i])
            if(len(strObjList) < 3):
                strList.append(strObjList.pop(0))
            elif i != len(seqList) - 1:
                tempstrObjList = strObjList.pop(-1)
                strList.extend(strObjList)
                strObjList = tempstrObjList
            else:
                strList.extend(strObjList)

    return strList

# 测试该函数
strObj = "笨鸟工具导航,www.x1y1z1.com"
strList1 = splitStr(strObj, True, "1")
print(strList1)
print("\n")
strList2 = splitStr(strObj, False, ",", ".")
print(strList2)

Tips:If you don’t understand or have any questions about this code, you can leave a comment. This is designed by myself and is a bit complicated.

Source:Stupid Bird Tool Navigation

Original text:How to split a string into multiple substrings in Python, multifunctional function design

Disclaimer: Content is for reference only! 

Guess you like

Origin blog.csdn.net/weixin_47378963/article/details/134962610