Home > database >  How can I filter between two positions in a string?
How can I filter between two positions in a string?

Time:03-20

I have this string:

__GENUS          : 2
__CLASS          : Win32_Process
__SUPERCLASS     :
__DYNASTY        :
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
CommandLine      : This is a Example 
                   Hello 789 123 abc
PSComputerName   :

But I only want a string from "This" to "abc" so that my string is:

This is a Example Hello 789 123 abc

Is there a way to do this?

CodePudding user response:

This will achieve what you are looking for ONLY if the number of colons (:) before the desired string is the same every time.

" ".join([i.strip() for i in bigstring.split(":")[11].split("\n")[:-1]])

Explanation

  1. Split the string up into list using bigstring.split(":")
  2. Get the 11th element of that list ('\n__PATH ', '\nCommandLine ', ' This is a Example \n Hello 789 123 abc\nPSComputerName ')
  3. Split that string up into a list using .split("\n")
  4. Use list comprehension to strip the whitespace from all but the last element of that list and put it into a new list.
  5. Use " ".join() to stick those elements together into the final string.

Output

This is a Example Hello 789 123 abc

I can't imagine that this is the best way to get the information you are looking for, but without any more context, this is the best I can do.

CodePudding user response:

You could use string indices to split the string into the area you want to use.

Code:

string = """
__GENUS          : 2
__CLASS          : Win32_Process
__SUPERCLASS     :
__DYNASTY        :
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
CommandLine      : This is a Example 
                   Hello 789 123 abc
PSComputerName   :"""

print_string_1 = string[int(len("""__GENUS          : 2
__CLASS          : Win32_Process
__SUPERCLASS     :
__DYNASTY        :
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
CommandLine      : """)):286]



print(print_string_1 )

Output:

 This is a Example
                   Hello 789 123 abc
Process finished with exit code 0
  • Related