简体   繁体   中英

Concatenate Python string within list

I ve some problem to concatenate a string with my list

I have some list like this:

my_device_list = ['Iphone', 'Samsung', 'Nokia','MI']

I want to join with the list so that i have output like this in a combined string within quotes as seen below:

combinedString = (Device_ID="Iphone" OR Device_ID="Samsung" OR Device_ID="Nokia" OR Device_ID="MI")

How would we concatenate string and those list together to a combined string?

I am trying like this and can add some string at the start but again getting them inside quotes each value converted back to string from list is little tricky and not working

 my_device_list = ['Iphone', 'Samsung', 'Nokia','MI']
    deviceString = 'Device_ID='
    combined__device_list = []
    final_combined_list =[]
    for x in my_device_list:
        combined__device_list.append(deviceString + x)
    final_combined_list = ' OR '.join(e for e in combined__device_list)

Can someone please help

Use f-string s in join for custom strings:

my_device_list = ['Iphone', 'Samsung', 'Nokia','MI']
deviceString = 'Device_ID'

out = ' OR '.join(f'{deviceString}="{e}"' for e in my_device_list)
print (out) 

Device_ID="Iphone" OR Device_ID="Samsung" OR Device_ID="Nokia" OR Device_ID="MI"

You may use the join method to get your output.

If you want an output like Iphone Samsung Nokia MI :

print(" ".join(my_device_list))

If you want an output like Iphone, Samsung, Nokia, MI :

print(", ".join(my_device_list))

Long story short, use Separator.join(List) to concatenate all items in a list.

Just change your

combined__device_list.append(deviceString + x)

To

combined__device_list.append(deviceString + "\"" + x + "\"")

You will get you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM