How to display the list with "" in python - 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!

Related

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

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

How to Append The Calculated Arithmetic to The List?

Let say we have this simple arithmetic:
y = 1 + 1
Can I append the result of the arithmetic to a list directly like so:
num_list = []
l = num_list.append(y)
I have tried to print the list to see if the result has been appended to the list, but I noticed it gives me "None" as output. Any idea how to approach this?
you should not print l, you should print num_list to see the appended list. Here is the sample test in python command line
>>> y = 1 + 1
>>> list1 = []
>>> list1.append(y)
>>> print list1
[2]
>>> print l
None
>>>

Use list comprehension to print out a list with words of length 4

I am trying to write a list comprehension that uses List1 to create a list of words of length 4.
List1 = ['jacob','batman','mozarella']
wordList = [words for i in range(1)]
print(wordList)
This prints out the wordList however with words of length higher than 4
I am looking for this program to print out instead:
['jaco','batm','moza']
which are the same words in List1 but with length 4
I tried this and it didn't work
wordList = [[len(4)] words for i in range(1)]
any thoughts ?
You could use this list comp
>>> List1 = ['jacob','batman','mozarella']
>>> [i[:4] for i in List1]
['jaco', 'batm', 'moza']
Ref:
i[:4] is a slice of the string of first 4 characters
Other ways to do it (All have their own disadvantages)
[re.sub(r'(?<=^.{4}).*', '', i) for i in List1]
[re.match(r'.{4}', i).group() for i in List1]
[''.join(i[j] for j in range(4)) for i in List1]
[i.replace(i[4:],'') for i in List1] ----- Fails in case of moinmoin or bongbong
Credit - Avinash Raj
len() function return the length of string in your case. So list compression with len function will give the list of all item lenght.
e.g.
>>> List1 = ['jacob','batman','mozarella']
>>> [len(i) for i in List1]
[5, 6, 9]
>>>
Use slice() list method to get substring from the string. more info
e.g.
>>> a = "abcdef"
>>> a[:4]
'abcd'
>>> [i[:4] for i in List1]
['jaco', 'batm', 'moza']
Python beginner
Define List1.
Define empty List2
Use for loop to iterate every item from the List1
Use list append() method to add item into list with slice() method.
Use print to see result.
sample code:
>>> List1 = ['jacob','batman','mozarella']
>>> List2 = []
>>> for i in List1:
... List2.append(i[:4])
...
>>> print List2
['jaco', 'batm', 'moza']
>>>
One more way, now using map function:
List1 = ['jacob','batman','mozarella']
List2 = map(lambda x: x[:4], List1)

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

Converting an integer list into a string list

I am new to Python. I need to know how to convert a list of integers to a list of strings. So,
>>>list=[1,2,3,4]
I want to convert that list to this:
>>>print (list)
['1','2','3','4']
Also, can I add a list of strings to make it look something like this?
1234
You can use List Comprehension:
>>> my_list = [1, 2, 3, 4]
>>> [str(v) for v in my_list]
['1', '2', '3', '4']
or map():
>>> str_list = map(str, my_list)
>>> str_list
['1', '2', '3', '4']
In Python 3, you would need to use - list(map(str, my_list))
For 2nd part, you can use join():
>>> ''.join(str_list)
'1234'
And please don't name your list list. It shadows the built-in list.
>>>l=[1,2,3,4]
I've modified your example to not use the name list -- it shadows the actual builtin list, which will cause mysterious failures.
Here's how you make it into a list of strings:
l = [str(n) for n in l]
And here's how you make them all abut one another:
all_together = ''.join(l)
Using print:
>>> mylist = [1,2,3,4]
>>> print ('{}'*len(mylist)).format(*mylist)
1234
l = map(str,l)
will work, but may not make sense if you don't know what map is
l = [str(x) for x in l]
May make more sense at this time.
''.join(["1","2","3"]) == "123"

Categories