简体   繁体   English

python split函数读取两个正斜杠之间的字符串

[英]python split function to read a string between two forward slashes

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. 我是python的新手,我试图编写一个脚本来打开文件,读取文件后会为我做一些自定义功能并将其存储在项目位置。 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 /... " “元素/ 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. 我发现split()相当容易实现。

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. 我相信它很简单,但是我在此上浪费了太多时间。

You can pass a delimiter to split, to clean the spaces you can them use the strip method.. 您可以传递定界符进行分割,以清理空间,您可以使用strip方法。

s = "element / read_this_string /... "

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

string_in_slashes
Out[13]: 'read_this_string'

To open a file in python, you can use python's with statement, which will handle file closing. 要在python中打开文件,您可以使用python的with语句,该语句将处理文件关闭。 and the for loop will take care of reading the file line by line. for循环将负责逐行读取文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM