0

Below lines are in A QPlainTextEdit:

enter image description here

I want to delete a matched line with line variable help. For example, I want to delete

line 2 s44 grade

with the help of line variable(line = "line 2")

I am able to delete the particular text with below code:

item = "line 2"
text = self.project_length_lanes_plainedit.toPlainText()
text = text.replace(item, '')
_list = text.split()
text = '\n'.join(_list)
self.project_length_lanes_plainedit.setPlainText(text)

but I want to delete the entire line. How can I do that?

Stidgeon
  • 2,673
  • 8
  • 20
  • 28
user3030327
  • 411
  • 1
  • 7
  • 19

2 Answers2

0

you have 2 basic options:

  1. use regexp to match whole line in your replace, then splitting lines is not necessary
  2. split to list first and remove matching line from list, and in the end join list as you did

EDIT:

import re

x = """
line1: abc
line2: def
line3: ghi
"""

print("regex:")
print(re.sub(r'line2.*', '', x))  # note: this leaves empty line
print("regex2:")
print(re.sub(r'line2.*\n', '', x))

print("list:")
print('\n'.join([line for line in x.split('\n') if "line2" not in line]))

konserw
  • 494
  • 2
  • 10
0

I tried as below working:

    item = "line 2"
    text = self.project_length_lanes_plainedit.toPlainText()
    for l in text.split('\n'):
        if item in l:
            text = text.replace(l, '')
            _list = text.split('\n')
            _list = [ i for i in _list if i ]
            text = '\n'.join(_list)
            self.project_length_lanes_plainedit.setPlainText(text)
user3030327
  • 411
  • 1
  • 7
  • 19