Home > Back-end >  Python - Convert a list into a modified string
Python - Convert a list into a modified string

Time:01-06

Thank you in advance for any help.

I have a list that will auto generate different values. An example is shown below.

[nan, 'RcLE858223862', 'ALTx674402122', 'XCvw626987396', 'Bdcp710236861']

I'm trying to find a way to convert this list into the following format

VariableValue = Value1=RcLE858223862&Value2=ALTx674402122&Value3=XCvw626987396&Value4=Bdcp710236861

The conversion will,

  1. Remove the null nan value,
  2. Count the number of values and have that count value be reflected in the Value (Value1, Value2, etc..)

Been trying for a few hours and still not having much luck.

Again, any advice is appreciated.

Thank you for your time.

CodePudding user response:

We can do this in two steps. First remove the nan values from the list. Then use a list comprehension to generate the output you want.

inp = [nan, 'RcLE858223862', 'ALTx674402122', 'XCvw626987396', 'Bdcp710236861']
inp = [i for i in inp if str(i) != "nan"]
lst = [f"Value{i 1}={inp[i]}" for i in range(len(inp))]
output = '&'.join(lst)
print(output)

# Value1=RcLE858223862&Value2=ALTx674402122&Value3=XCvw626987396&Value4=Bdcp710236861

CodePudding user response:

Something like?

>>> '&'.join([f'Value{j}={v}' for j, v in enumerate(
             [i for i in lst if i is not float(nan)], 1)])

'Value1=RcLE858223862&Value2=ALTx674402122&Value3=XCvw626987396&Value4=Bdcp710236861'
  • Related