簡體   English   中英

如何使用python刪除列表元素中的前14個字符?

[英]How can I strip the first 14 characters in an list element using python?

我有一個txt文件,我需要從中搜索正在運行的特定行,但是在該行中,我需要刪除前14個字符,並且我感興趣的list元素部分在運行時動態生成。 因此,方案是我運行了一個腳本並將輸出保存在output.txt中,現在我正在解析它,這是我嘗試過的

load_profile = open('output.txt', "r"
read_it = load_profile.read()
myLines = [ ]
for line in read_it.splitlines():
  if line.find("./testSuites/") > -1
   myLines.append(line)
print myLines

給出輸出: ['*** Passed :) at ./testSuites/TS1/2013/06/17/15.58.12.744_14']我需要解析./testSuites/TS1/2013/06/17/15.58.12.744_14'部分,並且字符串的2013和est是動態生成的。

你能指導我什么是最好的方法嗎?

在此先感謝Urmi

使用切片:

>>> strs = 'Passed :) at ./testSuites/TS1/2013/06/17/15.58.12.744_14'
>>> strs[13:]
'./testSuites/TS1/2013/06/17/15.58.12.744_14'

更新 :使用lis[0]訪問該列表內的字符串。

>>> lis = ['*** Passed :) at ./testSuites/TS1/2013/06/17/15.58.12.744_14']
>>> strs = lis[0]
>>> strs[17:]       # I think you need 17 here
'./testSuites/TS1/2013/06/17/15.58.12.744_14'

您正在問如何去除前14個字符,但是如果將來您的字符串不總是具有該格式怎么辦? 嘗試將字符串拆分為子字符串(除去空格),然后僅獲取帶有"./testSuites/"的子字符串。

load_profile = open('output.txt', "r")
read_it = load_profile.read()
myLines = [ ]
for line in read_it.splitlines():
    for splt in line.split():
        if "./testSuites/" in splt:
            myLines.append(splt)
print myLines

運作方式如下:

>>> pg = "Hello world, how you doing?\nFoo bar!"
>>> print pg
Hello world, how you doing?
Foo bar!
>>> lines = pg.splitlines()
>>> lines
["Hello world, how you doing?", 'Foo bar!']
>>> for line in lines:
...     for splt in line.split():
...             if "Foo" in splt:
...                     print splt
... 
Foo
>>> 

當然,如果你實際上對這些行的格式有嚴格要求,你可以只使用字符串的切片( strs[13:]作為阿什維尼說的),或者你可以分割線,做splt[-1]這意味着獲取分隔線列表的最后一個元素)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM