Home > Software design >  How to filter <str> by index 1,2,3.. in python
How to filter <str> by index 1,2,3.. in python

Time:04-04

I have three variable that store str value. Example:

dataTOcompare[dataTOcompare_index][0] = 'header1 : Subject', 'header2 :Text'

dataTOcompare[dataTOcompare_index][1] = 'condition1 : Equal', 'condition2: Contain '

dataTOcompare[dataTOcompare_index][2] = 'parameter1: hi1', 'parameter2: hi2'

What i trying to achieved:

I want it to pair each index 1,2,3 with three different str. For example, header1,condition1, parameter1 should be one data eg.

Expected output: header1, condition1, parameter1 =

Subject Equal hi1

header2, condition2, parameter2 =

Text Contain hi2

CodePudding user response:

You will have to split the string containing key-value pairs at :, then get the second value, which is the value of your key-value pair, strip the white spaces and then add them to the tuple. Using zip() you can iterate over multiple iterables at the same time.

input_header = 'header1 : Subject', 'header2 :Text'
input_conditions = 'condition1 : Equal', 'condition2: Contain '
input_parameters = 'parameter1: hi1', 'parameter2: hi2'


def getValue(string):
    return string.split(":")[1].strip()


result = [(getValue(header), getValue(condition), getValue(parameter)) for header, condition, parameter in
          zip(input_header, input_conditions, input_parameters)]
print(result)

Expected output:

[('Subject', 'Equal', 'hi1'), ('Text', 'Contain', 'hi2')]

You inputs though seem to be very quite odd. So if you can control it, just use simple arrays. Your key-value pairs as a string are not necessary as the key does not represent something meaningful and even if it was it is just a string not a dictionary that you can access easily using that key. You could use an array instead to achieve the same thing you are trying to do.

headers = ["Subject", "Text"]
conditions = ["Equal", "Contain"]
parameters = ["hi1", "hi2"]
result = list(zip(headers, conditions, parameters))

print(result)

This will produce the same output as what you have done above.

  • Related