简体   繁体   English

如果使用 Python 在该行中有某个字符,如何删除/忽略字符串中的整行?

[英]How to delete/ignore an entire line in a string if there is a certain character in that line using Python?

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"""

Create a generator, yielding that sring splitted by new line character.创建一个生成器,产生由换行符分割的字符串。 Instantiate that generator and in loop check it's output.实例化该生成器并在循环中检查它是 output。 If it (line) contains your special character, call next on the generator.如果它(行)包含您的特殊字符,请在生成器上调用 next。

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这将是 output 一个数组,每个元素都是字符串中的一行,现在循环该数组的内容,如果找到带有“$”的元素,只需将其删除

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还有另一种称为 strip() 的方法也可能适合您的需求,请尝试搜索

First, you can split the string into a list of lines using the splitlines function.首先,您可以使用拆分线 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.然后,您会将新列表与“\n”(换行符)重新组合成一个字符串。

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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