-1

If a multi-line string contains a certain character like '$', how can I erase/ignore the whole line that character reside?

Note: The task is to get rid of any lines containing a certain character and not empty lines.

testString = """unknown value 1
                unknown value 2
                unknown value 3
                $ unknown value 4
                unknown value 5"""
  • 1
    What have you tried so far? – Klaus D. Oct 31 '19 at 19:02
  • Possible duplicate of [What's a quick one-liner to remove empty lines from a python string?](https://stackoverflow.com/questions/1140958/whats-a-quick-one-liner-to-remove-empty-lines-from-a-python-string) – Sayse Oct 31 '19 at 19:02

3 Answers3

1

First, you can split the string into a list of lines using the splitlines function. Then, using list comprehension you can iterate through the lines and test each line for the presence of "$", and return a new list of lines without any lines containing "$". Then you would recombine the new list with "\n" (the newline character) back into a string.

Here is the code:

testString = """unknown value 1
                unknown value 2
                unknown value 3
                $ unknown value 4
                unknown value 5"""

newTestString = "\n".join([x.strip() for x in testString.splitlines() if "$" not in x])
cgahh12
  • 116
  • 3
0

Create a generator, yielding that sring splitted by new line character. Instantiate that generator and in loop check it's output. If it (line) contains your special character, call next on the generator.

0

first, split the string into an array in which each elemnt is a line

myLines = testString.splitlines()

this will output an array each element was a line in your string, now loop the contents of this array and if you find an element with '$' , just remove it

for line in myLines:
    for character in line:
       if character == '$'
          myLines.remove(line)

there's another method called strip() which may suit your needs too, try searching for it

Ahmed I. Elsayed
  • 2,013
  • 2
  • 17
  • 30