Home > Enterprise >  how to join items of a list in a defined manner in Python
how to join items of a list in a defined manner in Python

Time:01-20

I have a list as below:

mylist = ['L11_1','E12_3','F7_3']

What I want to do is to create a string based on the items of mylist as below:

mystring = df['L11_1'] df['E12_3'] df['F7_3']

What I have tried is not straightforward:

for i in mylist:
    mystring='df[' "'" i "'" '] '
    print(mystring,end='')

I tried to use the join() but was not sure how to define df[] with it. Any suggestions? Thank you.

CodePudding user response:

Is this what you're looking for? You can define the df using f-strings.

mystring = " ".join([f"df['{x}']" for x in mylist])
print(mystring)
>>> df['L11_1'] df['E12_3'] df['F7_3']

CodePudding user response:

mylist = ['L11_1','E12_3','F7_3']
string = " ".join([f"df['{i}']" for i in mylist])

output:

"df['L11_1'] df['E12_3'] df['F7_3']"
  •  Tags:  
  • Related