How to replace single quotes that appear when using split() function - python

I have a string, list1 that I'm converting to a list in order to compare it with another list, list2, to find common elements.
The following code works, but I need to replace ' with " in the final output, since it will be used in TOML front matter.
list1 = "a b c"
list1 = list1.split(" ")
print list1
>>> ['a','b','c']
list2 = ["b"]
print list(set(list1).intersection(list2))
>>> ['b']
**I need ["b"]**
New to python. I've tried using replace() and searched around, but can't find a way to do so. Thanks in advance.
I'm using Python 2.7.

Like any other structured text format, use a proper library to generate TOML values. For example
>>> import toml
>>> list1 = "a b c"
>>> list1 = list1.split(" ")
>>> list2 = ["b"]
>>> v = list(set(list1).intersection(list2))
>>> print(v)
['b']
>>> print(toml.dumps({"values": v}))
values = [ "b",]

made it
import json
l1 = "a b c"
l1 = l1.split(" ")
print(l1)
l2 = ["b"]
print(json.dumps(list(set(l1).intersection(l2))))
print(type(l1))
output:
['a', 'b', 'c']
["b"]
<type 'list'>

Related

Combine two lists without duplicate values

list1 = ["palani", "samy","be"]
list2 = ["palani", "samys","be"]
def find_common(list1,list2):
for x in list1:
for y in list2:
if x == y :
list2.remove(x)
print" unique string 1:",list1
print" unique string 2:",list2
print" combained string 2:",list1.append(list2)
find_common(list1,list2)
Why am I getting None?
This could be accomplished by using set:
a = ['hello', 'world']
b = ['hello', 'universe']
unique = list(set(a + b))
print(unique)
# ['universe', 'hello', 'world']
Note: this won't work for a list of dictionaries!
import numpy as np
np.unique(list1+list2) # keeps only non dublicates
this is also keeps the order incase that was a priority
The list.append method modifies the list in-place and returns None. You should use the + operator to merge the two lists instead.
Change:
print" combained string 2:",list1.append(list2)
to:
print" combained string 2:",list1+list2
list3 = list1[:]
[list3.append(i) for i in list2 if i not in list1]
print(l3)
['palani', 'samy', 'be', 'samys']
you may try:
def find_common(list1,list2):
return list(set(list1+list2))
You can use set operations to achieve this.
unique = list(set(list1).symmetric_difference(set(list2)))

How to display the list with "" in python

In Python it is allowed to use both '' and "" in the list.
And when I generate a list like:
map(str,list1)
the default display uses ' ':
mylist = ['1','2','3']
Now I want to display like :
mylist = ["1","2","3"]
How can I make it?
you can just replace the output after converting the list to a string:
>>> x = ['a','b']
>>> x
['a', 'b']
>>> y = str(x)
>>> y
"['a', 'b']"
>>> y.replace("'", '"')
'["a", "b"]'
note however, this is a string now, not a list.
You can also use the built-in string.format(). Try this:
>>> Mylist = [1, 2, 3]
>>> Mylist = ['"{}"'.format(x) for x in Mylist]
This will replace the {} with each element in Mylist and it to the new list , in its new format. You will get this result :
>>> Mylist
['"1"', '"2"', '"3"']
>>> print Mylist[0]
"1"
Hope this is what you are looking for, best of luck!

Append a portion of a string to a list

I was wondering how one can append a portion of a string to a list? Is there an option of both appending based on the position of characters in the string, and another option that is able to take a specific character of interest? For instance, If I had the string "2 aikjhakihaiyhgikjewh", could I not only append the part of the string that was in positions 3-4 but also append the "2" as well? I'm a beginner, so I'm still kinda new to this python thing. Thanks.
You can use slicing to reference a portion of a string like this:
>>> s = 'hello world'
>>> s[2:5]
'llo'
You can append to a list using the append method:
>>> l = [1,2,3,4]
>>> l.append('Potato')
>>> l
[1, 2, 3, 4, 'Potato']
Best way to learn this things in python is to open an interactive shell and start typing commands on it. I suggest ipython as it provides autocomplete which is great for exploring objects methods and properties.
You can append a portion of a string to a list by using the .append function.
List = []
List.append("text")
To append several parts of the string you can do the following:
List = []
String = "2 asdasdasd"
List.append(String[0:2] + String[3:5])
This would add both sections of the string that you wanted.
Use slicing to accomplish what you are looking for:
mystr = "2 aikjhakihaiyhgikjewh"
lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
print lst
This runs as:
>>> mystr = "2 aikjhakihaiyhgikjewh"
>>> lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
>>> print lst
['2', 'i', 'k']
>>>
Slicing works by taking certain parts of an object:
>>> mystr
'2 aikjhakihaiyhgikjewh'
>>> mystr[0]
'2'
>>> mystr[-1]
'h'
>>> mystr[::-1]
'hwejkighyiahikahjkia 2'
>>> mystr[:-5]
'2 aikjhakihaiyhgi'
>>>
You are describing 2 separate operations: slicing a string, and extending a list. Here is how you can put the two together:
In [26]: text = "2 aikjhakihaiyhgikjewh"
In [27]: text[0], text[3:5]
Out[27]: ('2', 'ik')
In [28]: result = []
In [29]: result.extend((text[0], text[3:5]))
In [30]: result
Out[30]: ['2', 'ik']

python expand a list to print

If I have a list
lst = ['A', 'B', 'C']
How do I expand it so that I can print something like
print '%s %s %s' % (*lst) ?
Thanks
These days, you'd use format instead:
"{} {} {}".format(*lst) #python 2.7 and newer
"{0} {1} {2}".format(*lst) #python 2.6 and newer
If you want to use string formatting the way you outlined, you have to convert the list to a tuple beforehand.
>>> l = ['A', 'B', 'C']
>>> print '%s %s %s' % tuple(l)
A B C
However, in this case I'd recommend something like
>>> print " ".join(l)
A B C
Shortened form of mgilson's answer, for code golf purposes
>>> l = ['A', 'B', 'C']
>>> print(*l)
A B C
>>> print '%s %s %s' % tuple(lst)
A B C
From the looks of it, your best bet is to use str.join:
lst = ['A', 'B', 'C']
print ' '.join(lst)
Use string.join(list) method:
print " ".join(lst)
This way the code won't break if list will have different number of elements.
Your question is abit unclear.. But if I understand correctly; you can add things to a list using append, and you can print your list using a simple print function. Example
list = ["A", "B", "C"]
list.append("D") #ADDS "D" TO THE LIST
print list #Will print all strings in list
Sorry if this doesn't help. I do what I can. (:

python list sort

I have got a list i.e.
ls= [u'Cancer',u"Men's",u'Orthopedics',u'Pediatric',u"Senior's",u"Women's"]
ls.sort() does not seem to work here due to presence of single quote in the list elements.
I need to sort this list. Any idea???
Actually, the question is valid and the answer is not exactly correct in general case.
If the test material was not already sorted, it would not get correctly alphabetized but the 's would cause the list to be sorted to wrong order:
>>> l = ["'''b", "a", "a'ab", "aaa"]
>>> l.sort()
>>> l
["'''b", 'a', "a'ab", 'aaa']
>>> from functools import partial
>>> import string
>>> keyfunc = partial(string.replace, old="'", new="")
>>> l.sort(key=keyfunc)
>>> l
['a', 'aaa', "a'ab", "'''b"]
>>> ls
[u'Cancer', u"Men's", u'Orthopedics', u'Pediatric', u"Senior's", u"Women's"]
>>> ls.sort()
>>> ls
[u'Cancer', u"Men's", u'Orthopedics', u'Pediatric', u"Senior's", u"Women's"]
Since the list was sorted in the first place, it didn't change. sort has no problem with ' - but note that it sorts before the a-z and A-Z characters:
>>> ls
[u'abc', u'abz', u"ab'"]
>>> ls.sort()
>>> ls
[u"ab'", u'abc', u'abz']
>>>

Categories