How to append a list withoud adding the quote - python

I have this code:
def add_peer_function():
all_devices=[]
all_devices.append("cisco,linux")
print(all_devices)
add_peer_function()
Which results in :
['cisco,linux']
My question is how can append the list without qota. So a result like this:
[cisco,router]

Well, I know two possible ways, but the first one is faster:
1:
def add_peer_function():
all_devices=[item for item in "cisco,linux".split(',')] # or `all_devices = ["cisco", "linux"]`
print(', '.join(all_devices)) # A prettier way to print list Thanks to Philo
add_peer_function()
2:
def add_peer_function():
all_devices=[]
for item in "cisco,linux".split(','): # or `all_devices = ["cisco", "linux"]`
all_devices.append(item)
print(', '.join(all_devices)) # A prettier way to print list Thanks to Philo
add_peer_function()
Python str.split documentation.
Python str.join documentation.
Python list comprehension documentation.

Python prints objects, by default, with its convention: strings are between quotes.
If you want to get another format, you can write your own formatter.
For lists of strings, a common pattern in Python is:
my_list = ['one', 'two', 'three']
print(', '.join(my_list))
Replace ', ' by another separator, eventually.
Finally, note that "cisco,linux" is just a string with a coma, which is different from a list of strings: ["cisco", "linux"].

Of course, if you append the string 'cisco,linux' to a list, you get ['cisco,linux'] which is the string representation of this list in Python.
What you what is to split the string.
Try:
>>> 'cisco,linux'.split(',')
['cisco', 'linux']

append accepts only one argument. so, your_list.append(something) will add something to your_list. you can however do sth like below.
your_list += [el for el in "cisco,linux".split(",")]

Related

How to replace comma with space in python list

I want to replace comma to space in the list. How can i do that? Thanks
input:
host_dict['actives'] = list(get_po_bound_ints['result'][1]['portChannels'][mac_to_eth2]['activePorts'].keys())
output:
[{'actives': ['PeerEthernet23',
'PeerEthernet24',
'Ethernet23',
'Ethernet22'],
Replacing commas with empty strings (assuming your list is named my_list):
print(str(my_list).replace(',', ''))
If I understand your question, you have an iterable that you want to convert to a space-separated string. The str.join method does that:
>>> test = ['PeerEthernet23', 'PeerEthernet24', 'Ethernet23', 'Ethernet22']
>>> " ".join(test)
'PeerEthernet23 PeerEthernet24 Ethernet23 Ethernet22'
your script would be
host_dict['actives'] = " ".join(get_po_bound_ints['result'][1]
['portChannels'][mac_to_eth2]['activePorts'].keys())

how to add apostrophe to elements in list which dont have it using Python

I have a list of strings and integers which are separated by commas however the integers dont have an apostrophe which I need. You can see some of the elements dont have the ''. Can someone help me put this in? thanks!
['BZ60830', 'BFEP3N8', 6039644, 'VNG6273', 56855557, 'B3SZGR6', 5575758, 'BYWJRH8']
data = ['BZ60830', 'BFEP3N8', 6039644, 'VNG6273', 56855557, 'B3SZGR6', 5575758, 'BYWJRH8']
data = [str(item) for item in data ]
print (data)
output:
['BZ60830', 'BFEP3N8', '6039644', 'VNG6273', '56855557', 'B3SZGR6', '5575758', 'BYWJRH8']
You can either map type str to your list
list(map(str, lst))
Alternative as suggested by #chepner without checking the type
lst_new = [str(i) for i in lst]

How do I excecute a command for every split?

I am new to python, and am trying to filter a string that looks similar to this:
"{Red,Plant,Eel}{Blue,Animal,Maple}{Yellow,Plant,Crab}"
And so on for 100s of three word sets.
I want to extract the second word from every set marked by "{ }", so in this example I want the output:
"Plant,Animal,Plant"
And so on.
How can I do it efficiently?
As of Right now I am using string.split(",")[1] individually for each "{ }" group.
Thanks.
This does the trick:
str_ = "{Red,Plant,Eel}{Blue,Animal,Maple}{Yellow,Plant,Crab}"
res = [x.split(',')[1] for x in str_[1:-1].split('}{')]
and produces
['Plant', 'Animal', 'Plant']
with the str_[1:-1] we remove the initial "{" and trailing "}" and we then split the remaining entities on every instance of "}{" thus producing:
["Red,Plant,Eel", "Blue,Animal,Maple", ...]
finally, for every string, we split on "," to obtain
[["Red", "Plant", "Eel"], ...]
from which we keep only the first element of each sublist with x[1].
Note that for your specific purpose, slicing the original string with str_[1:-1] is not mandatory (works without it as well), but if you wanted only the first instead of the second item it would make a difference. The same holds in case you wanted the 3rd.
If you want to concatenate the strings of the output to match your desired result, you can simply pass the resulting list to .join as follows:
out = ','.join(res)
which then gives you
"Plant,Animal,Plant"
Try This:
[i.split(',')[1] for i in str_[1:].split('}')[:len(str_.split('}'))-1]]
another solution is using regex, a bit more complicated, but it's a technique worth talking about:
import re
input_string = "{Red,Plant,Eel}{Blue,Animal,Maple}{Yellow,Plant,Crab}"
regex_string = "\{\w+\,(\w+)\,\w+\}"
result_list = re.findall(regex, input_string)
then result_list output is:
['Plant', 'Animal', 'Plant']
here's a link for regex in python
and an online regex editor
#!/bin/python3
string = "{Red,Plant,Eel}{Blue,Animal,Maple}{Yellow,Plant,Crab}"
a = string.replace('{','').replace('}',',').split(',')[1::3]
print(a)
result is
['Plant', 'Animal', 'Plant']

python parsing a string

I have a list with strings.
list_of_strings
They look like that:
'/folder1/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file'
I want to part this string into:
/folder1/folder2/folder3/folder4/folder5/exp-* and put this into a new list.
I thought to do something like that, but I am lacking the right snippet to do what I want:
list_of_stringparts = []
for string in sorted(list_of_strings):
part= string.split('/')[7] # or whatever returns the first part of my string
list_of_stringparts.append(part)
has anyone an idea? Do I need a regex?
You are using array subscription which extracts one (eigth) element. To get first seven elements, you need a slicing [N:M:S] like this:
>>> l = '/folder1/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file'
>>> l.split('/')[:7]
['', 'folder1', 'folder2', 'folder3', 'folder4', 'folder5', 'exp-*']
In our case N is ommitted (by default 0) and S is step which is by default set to 1, so you'll get elements 0-7 from the result of split.
To construct your string back, use join():
>>> '/'.join(s)
'/folder1/folder2/folder3/folder4/folder5/exp-*'
I would do like this,
>>> s = '/folder1/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file'
>>> s.split('/')[:7]
['', 'folder1', 'folder2', 'folder3', 'folder4', 'folder5', 'exp-*']
>>> '/'.join(s.split('/')[:7])
'/folder1/folder2/folder3/folder4/folder5/exp-*'
Using re.match
>>> s = '/folder1/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file'
>>> re.match(r'.*?\*', s).group()
'/folder1/folder2/folder3/folder4/folder5/exp-*'
Your example suggests that you want to partition the strings at the first * character. This can be done with str.partition():
list_of_stringparts = []
list_of_strings = ['/folder1/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file', '/folder1/exp-*/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file', '/folder/blah/pow']
for s in sorted(list_of_strings):
head, sep, tail = s.partition('*')
list_of_stringparts.append(head + sep)
>>> list_of_stringparts
['/folder/blah/pow', '/folder1/exp-*', '/folder1/folder2/folder3/folder4/folder5/exp-*']
Or this equivalent list comprehension:
list_of_stringparts = [''.join(s.partition('*')[:2]) for s in sorted(list_of_strings)]
This will retain any string that does not contain a * - not sure from your question if that is desired.

Split a string in python

a="aaaa#b:c:"
>>> for i in a.split(":"):
... print i
... if ("#" in i): //i=aaaa#b
... print only b
In the if loop if i=aaaa#b how to get the value after the hash.should we use rsplit to get the value?
The following can replace your if statement.
for i in a.split(':'):
print i.partition('#')[2]
>>> a="aaaa#b:c:"
>>> a.split(":",2)[0].split("#")[-1]
'b'
a = "aaaa#b:c:"
print(a.split(":")[0].split("#")[1])
I'd suggest from: Python Docs
str.rsplit([sep[, maxsplit]])
Return a list of the words in the string, using sep as the delimiter
string. If maxsplit is given, at most maxsplit splits are done, the
rightmost ones. If sep is not specified or None, any whitespace string
is a separator. Except for splitting from the right, rsplit() behaves
like split() which is described in detail below.
so to answer your question yes.
EDIT:
It depends on how you wish to index your strings too, it looks like Rstring does it from the right, so if your data is always "rightmost" you could index by 0 (or 1, not sure how python indexes), every time, rather then having to do a size check of the returned array.
do you really need to use split? split create a list, so isn't so efficient...
what about something like this:
>>> a = "aaaa#b:c:"
>>> a[a.find('#') + 1]
'b'
or if you need particular occurence, use regex instead...
split would do the job nicely. Use rsplit only if you need to split from the last '#'.
a="aaaa#b:c:"
>>> for i in a.split(":"):
... print i
... b = i.split('#',1)
... if len(b)==2:
... print b[1]

Categories