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-strings 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.
Related
I am trying to simply replace a list item with another item, except the new item has a space in it. When it replaces, it creates two list items when I only want one. How can I make it just one item in the list please?
Here is a minimal reproducible example:
import re
cont = "BECMG 2622/2700 32010KT CAVOK"
actual = "BECMG 2622"
sorted_fm_becmg = ['BECMG 262200', '272100']
line_to_print = 'BECMG 262200'
becmg = re.search(r'%s[/]\d\d\d\d' % re.escape(actual), cont).group()
new_becmg = "BECMG " + becmg[-4:] + "00" # i need to make this one list item when it replaces 'line_to_print'
sorted_fm_becmg = (' '.join(sorted_fm_becmg).replace(line_to_print, new_becmg)).split()
print(sorted_fm_becmg)
I need sorted_fm_becmg to look like this : ['BECMG 270000', '272100'].
I've tried making new_becmg a list item, I have tried removing the space in the string in new_becmg but I need the list item to have a space in it.
It is probably something simple but I can't get it. Thank you.
You can iterate through sorted_fm_becmg to replace each string individually instead:
sorted_fm_becmg = [b.replace(line_to_print, new_becmg) for b in sorted_fm_becmg]
I have a list i need to .join as string and append characters
my_list = ['3.3.3.3', '2.2.2.3', '2.2.2.2']
my_list.append(')"')
my_list.insert(0,'"(')
hostman = '|'.join('{0}'.format(w) for w in my_list)
#my_list.pop()
print(hostman)
print(my_list)
My output = "(|3.3.3.3|2.2.2.3|2.2.2.2|)"
I need the output to be = "(3.3.3.3|2.2.2.3|2.2.2.2)"
how can i strip the first and last | from the string
You are making it harder than it needs to be. You can just use join() directly with the list:
my_list = ['3.3.3.3', '2.2.2.3', '2.2.2.2']
s = '"(' + '|'.join(my_list) + ')"'
# s is "(3.3.3.3|2.2.2.3|2.2.2.2)"
# with quotes as part of the string
or if you prefer format:
s = '"({})"'.format('|'.join(my_list))
Try this :
hostman = "("+"|".join(my_list)+")"
OUTPUT :
'(3.3.3.3|2.2.2.3|2.2.2.2)'
Using this code I was able to cycle through several instances of attributes and extract First and Last name if they matched the criteria. The results are a list of dict. How would i make all of these results which match the criteria, return as a full name each on it's own line as text?
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
print({players['firstName'], players['lastName']})
Results of Print Statement
{'Chandon', 'Sullivan'}
{'Urban', 'Brent'}
Are you looking for this:
print(players['firstName'], players['lastName'])
This would output:
Chandon Sullivan
Urban Brent
Your original trial just put the items to a set {}, and then printed the set, for no apparent reason.
Edit:
You can also for example join the firstName and lastName to be one string and then append the combos to a lists. Then you can do whatever you need with the list:
names = []
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
names.append(f"{players['firstName']} {players['lastName']}")
If you're using a version of Python lower than 3.6 and can't use f-strings you can do the last line for example like this:
names.append("{} {}").format(players['firstName'], players['lastName'])
Or if you prefer:
names.append(players['firstName'] + ' ' + players['lastName'])
Ok I figured out by appending the first and last name and creating a list for the found criteria. I then converted the list to a string to display it on the device.
full_list = []
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
full_list.append((players['firstName'] + " " + players['lastName']))
send_message('\n'.join(str(i) for i in full_list))
i'm new to python and i'm having a select statement like following help_category_id, name, what is the most effective way to convert this string to this:
'help_category_id', 'name'
i've currently done this, which works fine, but is there a nicer and more clean way to do the same:
test_string = 'help_category_id, name'
column_sort_list = []
if test_string is not None:
for col in test_string.split(','):
column = "'{column}'".format(column=col)
column_sort_list.append(column)
column_sort = ','.join(column_sort_list)
print(column_sort)
Simple one liner using looping constructs:
result = ", ".join(["'" + i + "'" for i.strip() in myString.split(",")])
What we are doing here is we are creating a list that contains all substrings of your original string, with the quotes added. Then, using join, we make that list into a comma delimited string.
Deconstructed, the looping construct looks like this:
resultList = []
for i in myString.split(","):
resultList.append("'" + i.strip() + "'")
Note the call to i.strip(), which removes extraneous spaces around each substring.
Note: You can use format syntax to make this code even cleaner:
New syntax:
result = ", ".join(["'{}'".format(i.strip()) for i in myString.split(",")])
Old syntax:
result = ", ".join(["'%s'" % i.strip() for i in myString.split(",")])
it can be achieved by this also.
','.join("'{}'".format(value) for value in map(lambda text: text.strip(), test_string.split(",")))
I am using the below code that split a bit of text at the first space
splitdata = details[2].split(' ', 1)
details[2] = splitdata[0]
details.extend(splitdata[1:])
so will take a string like:
['(Class 6)', '(0-60, 4yo+)', '1m4f Standard']
and it amends it to:
['(Class 6)', '(0-65, 4yo+)', '1m4f', 'Standard']
but i would like the distance to be last. I have played around with the code and looked up multiple tutorials and im sure its easy to do but i have i don't seem to know how to get it to look like the below:
['(Class 6)', '(0-65, 4yo+)', 'Standard', '1m4f']
Instead of your last two lines:
details[2:] = reversed(splitdata)
Use some python swapping like this,
details = ['(Class 6)', '(0-60, 4yo+)', '1m4f Standard']
splitdata = details[2].split(' ', 1)
details[2] = splitdata[0]
details.extend(splitdata[1:])
details[2], details[3] = details[3], details[2] # Swap
print details
Do you need opposite order of two last elements? If yes, just change order of indices:
splitdata = details[2].split(' ', 1)
details[2] = splitdata[1]
details.extend(splitdata[0])