删除数据中特定字符串的最佳方法是什么?

时间:2017-10-03 17:31:10

标签: python python-2.7 python-3.x pandas

任何人都能以最佳方式帮助我以编程方式删除数据中的以下字符串吗?提前谢谢。

我的TextFile:

-------------------------------------------- 

-       All Data Monthly        - 

-------------------------------------------- 

Local date-time is [2017-10-03 04:05:18.531] 

-------------------------------------------- 

C NUMBER                   |SR LOCATION     |COUNTY                                                                                
1234                       |SFO             |IND

我想使用python程序删除数据中的以下字符串。字符串格式保持不变但值更改

 -------------------------------------------- 

-       All Data Monthly        - 

-------------------------------------------- 

Local date-time is [2017-10-03 04:05:18.531] 

-------------------------------------------- 

请帮帮我。谢谢

3 个答案:

答案 0 :(得分:1)

# a simple approach that assumes the unwanted header occurs once at
# the top of the file.
with open('s.py') as f:
    for i, line in enumerate(f):
        if i < 10: continue
        print line.rstrip() # or whatever

答案 1 :(得分:1)

首先,您需要在字符串中找到要修剪的部分的索引,例如:

str1 = "this is string example....wow!!!"
str2 = "exam"
print str1.find(str2) 

这将给你15这是&#34;考试&#34;的索引。在这个字符串

如果python找不到原始字符串中的字符串,它将返回-1,因此使用if语句相应地采用你的代码

现在你只需要通过做类似的事情来获取原始字符串的子字符串。

subString = str1[:15]

这会将subString分配给&#34; hello&#34;

的新值

您可以通过查找字符串中的任何索引并修剪字符串

的任何部分来执行相同操作
original_string[start-index:end-index]
祝你好运

答案 2 :(得分:1)

import datetime as dt

lines=[]

#Open testfile.txt and append all the content into a list
with open("testfile.txt", "r") as file:
    for line in file:
        #To remove the '\n' at the end of every line
        lines.append(line.replace('\n', '')
#slicing the list containing the contents of 'testfile.txt' so that only the required stuff remains.
lines=lines[:9]
#I just added this to change the "local date-time is..." line and put the current date-time.
lines[6]=("Local date-time is [{}]".format(dt.datetime.now()))

#Finally, write all of the content into testfile.txt
with open("testfile.txt", "w") as file:
    for line in lines:
        file.write(str(line)+'\n')

我希望评论行足以解释代码的作用。如果没有,请评论下来,我会尝试解释。