简体   繁体   中英

Remove substring from a string in python

I have got a file in python with filenames. I want to delete some lines and some substirng of the filename using python code. My file format is the above:

img/1.jpg
img/10.jpg
img/100.jpg 0 143 84 227
...

I want to delete the img/substring from all the file and the lines where the coordinates are missing. For the second task I did the following:

for con in content:
  if ".jpg\n" in con:
        content.remove(con)

for con in content:
    print con

However content didn't change.

You're attempting to modify the list content while iterating over it. This will very quickly bite you in the knees.

Instead, in python you generate a new list:

>>> content = [fn for fn in content if not fn.endswith(".jpg\n")]
>>> 

After this you can overwrite the file you read from with the contents from... contents . The above example assumes there is no whitespace to accomodate for in between the filename and the newline.

The error in your current method is because you are iterating through each line by letter , for l in somestring: will go letter by letter. Obviously, a ".jpg\\n" won't be in a single letter, so you never hit content.remove(con) .

I would suggest a slightly different approach:

with open("fileofdata.txt", 'r') as f:
    content = [line for line in f.readlines() if len(line.split()) > 1]

Using len(line.split()) is more robust than line.endswith() because it allows for withspace between .jpg and \\n .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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