Apex
Apex

Reputation: 1096

how to join items of a list in a defined manner in Python

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.

Upvotes: 0

Views: 53

Answers (2)

Tal Folkman
Tal Folkman

Reputation: 2581

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']"

Upvotes: 1

Jan Jaap Meijerink
Jan Jaap Meijerink

Reputation: 447

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']

Upvotes: 3

Related Questions