python expand a list to print - python

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. (:

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

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

Print list without spaces

I have this code here. I want to print a list without spaces. Here l is a list with 3 elements that I am trying to print:
>>> l=[]
>>> l.append(5)
>>> l.append(6)
>>> l.append(7)
>>> print(l)
I get in the output:
[5, 6, 7]
but I want to get:
[5,6,7]
What should I add to the syntax in append or in print to print the list without spaces?
You need to use something like:
print('[{0}]'.format(','.join(map(str, l))))
You can modify the result if it isn't too big:
print(repr(l).replace(' ', ''))
You could convert it to a string and then replace the spaces. E.g:
print ("{}".format(l)).replace(' ', '')
Join the list elements.
print("[" + ",".join([str(i) for i in l]) + "]")

How to "properly" print a list?

So I have a list:
['x', 3, 'b']
And I want the output to be:
[x, 3, b]
How can I do this in python?
If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".
This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
If you are using Python3:
print('[',end='');print(*L, sep=', ', end='');print(']')
Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:
def get_nice_string(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.
You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate() function will also work in 2.6+, so using it might be preferable.
Here's an interactive session showing some of the steps in #TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)
Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.
>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'
Using .format for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map is used to map each element of the list to string type.
The elements are joined together into a string with , as separator.
We use [ and ] in the print statement to show the list braces.
Reference:
.format for string formatting PEP-3101
I was inspired by #AniMenon to write a pythonic more general solution.
mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))
It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format.
For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f
mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))
The output is quite decent:
[1.85, -6.33, 4000.21]

Format all elements of a list

I want to print a list of numbers, but I want to format each member of the list before it is printed.
For example,
theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]
I want the following output printed given the above list as an input:
[1.34, 7.42, 6.97, 4.55]
For any one member of the list, I know I can format it by using
print "%.2f" % member
Is there a command/function that can do this for the whole list? I can write one, but was wondering if one already exists.
If you just want to print the numbers you can use a simple loop:
for member in theList:
print "%.2f" % member
If you want to store the result for later you can use a list comprehension:
formattedList = ["%.2f" % member for member in theList]
You can then print this list to get the output as in your question:
print formattedList
Note also that % is being deprecated. If you are using Python 2.6 or newer prefer to use format.
For Python 3.5.1, you can use:
>>> theList = [1.343465432, 7.423334343, 6.967997797, 4.5522577]
>>> strFormat = len(theList) * '{:10f} '
>>> formattedList = strFormat.format(*theList)
>>> print(formattedList)
The result is:
' 1.343465 7.423334 6.967998 4.552258 '
A very short solution using "".format() and a generator expression:
>>> theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]
>>> print(['{:.2f}'.format(item) for item in theList])
['1.34', '7.42', '6.97', '4.55']
You can use list comprehension, join and some string manipulation, as follows:
>>> theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]
>>> def format(l):
... return "["+", ".join(["%.2f" % x for x in l])+"]"
...
>>> format(theList)
'[1.34, 7.42, 6.97, 4.55]'
You can use the map function
l2 = map(lambda n: "%.2f" % n, l)
Try this one if you don't need to save your values:
list = [0.34555, 0.2323456, 0.6234232, 0.45234234]
for member in list:
form='{:.1%}'.format(member)
print(form)
output:
34.6%
23.2%
62.3%
45.2%
You can use helper function:
def format_list(a, fmt, sep=', ', start='[', end=']'):
return start + sep.join([format(x, fmt) for x in a]) + end
usage:
a=[4,8,15,16,23,42]
print(f"%d is {format_list(a, 'd')} %x is {format_list(a, 'x')} %b is {format_list(a, 'b')}")

Categories