'How can I filter between two positions in a string?
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?
Solution 1:[1]
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
- Split the string up into list using
bigstring.split(":") - Get the 11th element of that list (
'\n__PATH ', '\nCommandLine ', ' This is a Example \n Hello 789 123 abc\nPSComputerName ') - Split that string up into a list using
.split("\n") - Use list comprehension to strip the whitespace from all but the last element of that list and put it into a new list.
- 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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Evyn |
| Solution 2 | Blue Robin |
