Home > Back-end >  Python 3 split string multiple times
Python 3 split string multiple times

Time:12-11

Text file input:

10G/Host_IP,UID,PWD,Host-Name,15-2-7

10G/Host_IP,UID,PWD,Host-Name,12-2-7

root = tk.Tk()
root.attributes("-topmost", True) 
root.withdraw()
file = tkinter.filedialog.askopenfilename()

def _10g_script (params):

    print (type(params))   ## says params is a str


    for items in params:
        params1 = items.split(",")
##    print(IP, UID, PWD, TID, SH_SL_PT)   ## is what I am wanting here, 
                                           ##then I will split the SH_SL_PT
        print (type(params1))  ## says params is a list


with open(file,"r") as fh:
    for lines in fh:
        rate, param = lines.strip().split("/")
        
        if rate == "10G":
            _10g_script(param)
           print (type(param))  ## says param is a str

What I am trying to is split the line from the text file the rate and the rest of the parameters, rate and other parameters into separate variables. Pass the rate into the function then split the variable params further into more variables (Host_IP, UID, PWD, Host-Name, SH_SL_PT).

The first split in is a str and after the split, but when I try the second split it says it is a list.

I have tried join, but it puts every character as its own string with a "," in between characters

Any help would be appreciated

CodePudding user response:

Let's walk through the code. Your code starts here:

with open(file,"r") as fh:
for lines in fh:
    rate, param = lines.strip().split("/")
    
    if rate == "10G":
        _10g_script(param)
       print (type(param))  ## says param is a str

We first open the file and then jump into the for loop. This loop splits up the document into lines, and puts these lines into a list that it goes through, meaning that the variable lines is a string of one line of the document, and every iteration we go to the next line.

Next we split the our line using "/". This split creates a list containing two elements, with lines.strip().split("/") = ["10G","Host_IP,UID,PWD,Host-Name,12-2-7"]. However, on the left side you put two variables, rate and param, so python sets rate = "10G" and param = "Host_IP,UID,PWD,Host-Name,12-2-7".

Going into your function, params as you saw is a string. So when you try to loop through it, python assumes that you want each iteration of your loop to go through a single character.

So, instead of writing the function _10g_script, what you can do is:

with open(file,"r") as fh:
for lines in fh:
    rate, param = lines.strip().split("/")
    
    if rate == "10G":
       #IP = "Host_IP", UID = "UID", TID = "TID", SH_SL_PT  
       IP, UID, PWD, TID, SH_SL_PT = param.split(",") 
       print(IP,UID,TID,SH_SL_PT)

Then you would do the same for SH_SL_PT, writing:

SH,SL,PT = SH_SL_PT.split("-") 

Wherever you needed that.

  • Related