python split function to read a string between two forward slashes

5.5k views Asked by At

I am very new to python, i am trying to write a script which opens a file, read the file do some custom function for me and store it in project location. Meanwhile i am facing trouble to read the file line by line and find the string in between the two forward slashes. like in the example shown below i want the script to read the "string between the slashes".

"element / read_this_string /... "

I did go through some hints provided online, as in to use Regular expression or use split function. I found split() rather easy to implement.

I would really appreciate if someone could help me with this problem i am stuck with. I am sure its a simple one but i am wasting too much time on this.

2

There are 2 answers

3
slcjordan On BEST ANSWER

To open a file in python, you can use python's with statement, which will handle file closing. and the for loop will take care of reading the file line by line.

with open("file.txt") as f:
    for line in f:
        if len(line.split("/")) > 1:
            print(line.split("/")[1])
0
canesin On

You can pass a delimiter to split, to clean the spaces you can them use the strip method..

s = "element / read_this_string /... "

string_in_slashes = s.split('/')[1].strip()

string_in_slashes
Out[13]: 'read_this_string'