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')}")
Related
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]) + "]")
Suppose I had a string
string1 = "498results should get"
Now I need to get only integer values from the string like 498. Here I don't want to use list slicing because the integer values may increase like these examples:
string2 = "49867results should get"
string3 = "497543results should get"
So I want to get only integer values out from the string exactly in the same order. I mean like 498,49867,497543 from string1,string2,string3 respectively.
Can anyone let me know how to do this in a one or two lines?
>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498
If there are multiple integers in the string:
>>> map(int, re.findall(r'\d+', string1))
[498]
An answer taken from ChristopheD here: https://stackoverflow.com/a/2500023/1225603
r = "456results string789"
s = ''.join(x for x in r if x.isdigit())
print int(s)
456789
Here's your one-liner, without using any regular expressions, which can get expensive at times:
>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))
returns:
'123453120'
if you have multiple sets of numbers then this is another option
>>> import re
>>> print(re.findall('\d+', 'xyz123abc456def789'))
['123', '456', '789']
its no good for floating point number strings though.
Iterator version
>>> import re
>>> string1 = "498results should get"
>>> [int(x.group()) for x in re.finditer(r'\d+', string1)]
[498]
>>> import itertools
>>> int(''.join(itertools.takewhile(lambda s: s.isdigit(), string1)))
With python 3.6, these two lines return a list (may be empty)
>>[int(x) for x in re.findall('\d+', your_string)]
Similar to
>>list(map(int, re.findall('\d+', your_string))
this approach uses list comprehension, just pass the string as argument to the function and it will return a list of integers in that string.
def getIntegers(string):
numbers = [int(x) for x in string.split() if x.isnumeric()]
return numbers
Like this
print(getIntegers('this text contains some numbers like 3 5 and 7'))
Output
[3, 5, 7]
def function(string):
final = ''
for i in string:
try:
final += str(int(i))
except ValueError:
return int(final)
print(function("4983results should get"))
Another option is to remove the trailing the letters using rstrip and string.ascii_lowercase (to get the letters):
import string
out = [int(s.replace(' ','').rstrip(string.ascii_lowercase)) for s in strings]
Output:
[498, 49867, 497543]
integerstring=""
string1 = "498results should get"
for i in string1:
if i.isdigit()==True
integerstring=integerstring+i
print(integerstring)
I have a list of tuples of form
[("very", "ADJ"), ("slow", "ADJ"), ("programmer", "NOUN")]
My desired output is a single string of form:
"very/ADJ slow/ADJ programmer/NOUN"
This being python, I know I can do this in a one-liner using the format() and join() methods, but I can't get the syntax quite right. My most recent attempt was:
output_string = " ".join(["{0}/{1}".format(x) for x in list_of_tuples])
which threw an Index Error: tuple index out of range"
You want format(*x) so that the x tuple is expanded into arguments. Otherwise you are trying to call format with a single argument which is itself a tuple.
That said, if you know that these are all 2-tuples, I'd just go with the simpler:
output_string = " ".join(a + "/" + b for a, b in list_of_tuples)
Also note that there's no need to use a list comprehension to pass into join -- just use a generator comprehension instead.
words = [("very", "ADJ"), ("slow", "ADJ"), ("programmer", "NOUN")]
' '.join('/'.join((x,y)) for x,y in words)
You can use map too:
>>> ' '.join(map(lambda t: '{}/{}'.format(*t), li))
'very/ADJ slow/ADJ programmer/NOUN'
And, that same method without the lambda:
>>> ' '.join(map('/'.join, li))
'very/ADJ slow/ADJ programmer/NOUN'
Which works even if you have more than two elements in your tuples.
I have a nested list as below:
[['asgy200;f','ssll100',' time is: 10h:00m:12s','xxxxxxx','***','','asgy200;f','frl5100',' time is: 00h:00m:05s','ooo']]
'***' is my delimiter. I want to separate all of seconds in the list in python.
First of all with regular expression I want to separate the line that has time is: string but it doesn't work!
I don't know what should I do.
Thanks
import re
x=[['asgy200;f','ssll100','time is: 10h:00m:12s','xxxxxxx','***','','asgy200;f','frl5100','time is: 00h:00m:05s','ooo']]
s=str(x)
print re.findall(r"(?<=time is)\s*:\s*[^']*:(\d+)",s)
Output:['12', '05']
You can try this.
You can use a look-ahead regex (r'(?<=time is\:).*') :
>>> [i.group(0).split(':')[2] for i in [re.search(r'(?<=time is\:).*',i) for i in l[0]] if i is not None]
['12s', '05s']
and you can convert them to int :
>>> [int(j.replace('s','')) for j in sec]
[12, 5]
if you want the string of seconds don't convert them to int after replace :
>>> [j.replace('s','') for j in sec]
['12', '05']
You could use capturing groups also. It won't print the seconds if the seconds is exactly equal to 00
>>> lst = [['asgy200;f','ssll100','time is: 10h:00m:12s','xxxxxxx','***','','asgy200;f','frl5100','time is: 00h:00m:05s','ooo']]
>>> [i for i in re.findall(r'time\s+is:\s+\d{2}h:\d{2}m:(\d{2})', ' '.join(lst[0])) if int(i) != 00]
['12', '05']
>>> lst = [['asgy200;f','ssll100','time is: 10h:00m:00s','xxxxxxx','***','','asgy200;f','frl5100','time is: 00h:00m:05s','ooo']]
>>> [i for i in re.findall(r'time\s+is:\s+\d{2}h:\d{2}m:(\d{2})', ' '.join(lst[0])) if int(i) != 00]
['05']
Taking into account your last comment to your Q,
>>> x = [['asgy200;f','ssll100','time is: 10h:00m:12s','xxxxxxx','***','','asgy200;f','frl5100','time is: 00h:00m:05s','ooo']]
>>> print all([w[-3:-1]!='00' for r in x for w in r if w.startswith('time is: ')])
True
>>>
all and any are two useful builtins...
The thing operates like this, the slower loop is on the sublists (rows) of x, the fastest loop on the items (words)in each row, we pick up only the words that startswith a specific string, and our iterable is made of booleans where we have true if the 3rd last and 2nd last character of the picked word are different from'00'. Finally the all consumes the iterable and returns True if all the second fields are different from '00'.
HTH,
Addendum
Do we want to break out early?
all_secs_differ_from_0 = True
for row in x:
for word in row:
if word.startswith('time is: ') and word[-3:-1] == '00':
all_secs_differ_from_0 = False
break
if not all_secs_differ_from_0: break
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]) + "]")