I wrote code to append a json response into a list for some API work I am doing, but it stores the single quotes around the alphanumerical value I desire. I would like to get rid of the single quotes. Here is what I have so far:
i = 0
deviceID = []
while i < deviceCount:
deviceID.append(devicesRanOn['resources'][i])
deviceID[i] = re.sub('[\W_]', '', deviceID[i])
i += 1
if i >= deviceCount:
break
if (deviceCount == 1):
print ('Device ID: ', deviceID)
elif (deviceCount > 1):
print ('Device IDs: ', deviceID)
the desired input should look like this:
input Device IDs:
['14*************************00b29', '58*************************c3df4']
Output:
['14*************************00b29', '58*************************c3df4']
Desired Output:
[14*************************00b29, 58*************************c3df4]
As you can see, I am trying to use RegEx to filter non Alphanumeric and replace those with nothing. It is not giving me an error nor is it preforming the actions I am looking for. Does anyone have a recommendation on how to fix this?
Thank you,
xOm3ga
You won't be able to use the default print. You'll need to use your own means of making a representation for the list. But this is easy with string formatting.
'[' + ', '.join(f'{id!s}' for id in ids) + ']'
The f'{id:!s} is an f-string which formats the variable id using it's __str__ method. If you're on a version pre-3.6 which doesn't use f-strings, you can also use
'%s' % id
'{!s}'.format(id)
PS:
You can simplify you're code significantly by using a list comprehension and custom formatting instead of regexes.
ids = [device for device in devicesRanOn['resources'][:deviceCount]]
if deviceCount == 1:
label = 'Device ID:'
elif deviceCount > 1:
label = 'Device IDs:'
print(label, '[' + ', '.join(f'{id!s}' for id in ids) + ']')
Related
With this python's code I may read all tickers in the tickers.txt file:
fh = open("tickers.txt")
tickers_list = fh.read()
print(tickers_list)
The output that I obtain is this:
A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI,
Neverthless, I'd like to obtain as ouput a ticker string exactly formatted in this manner:
["A2A.MI", "AMP.MI", "ATL.MI", "AZM.MI", ...]
Any idea?
Thanks in advance.
If you want the output to look in that format you want, you would need to do the following:
tickers_list= "A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI"
print("["+"".join(['"' + s + '",' for s in tickers_list.split(",")])[:-1]+"]")
With the output:
["A2A.MI"," AMP.MI"," ATL.MI"," AZM.MI"," BGN.MI"," BMED.MI"," BAMI.MI"]
Code explanation:
['"' + s + '",' for s in tickers_list.split(",")]
Creates a list of strings that contain each individual value, with the brackets as well as the comma.
"".join(...)[:-1]
Joins the list of strings into one string, removing the last character which is the extra comma
"["+..+"]"
adds the closing brackets
Another alternative is to simple use:
print(tickers_list.split(","))
However, the output will be slightly different as in:
['A2A.MI', ' AMP.MI', ' ATL.MI', ' AZM.MI', ' BGN.MI', ' BMED.MI', ' BAMI.MI']
Having ' instead of "
A solution for that however is this:
z = str(tickers_list.split(","))
z = z.replace("'",'"')
print(z)
Having the correct output, by replacing that character
you can to use Split function:
tickers_list = fh.read().split(',')
I'm trying to display values in HTML that have a "$" at the beginning, but the way I print out the values in HTML makes it so that with the justification I can only add it at the end of the previous value or at the end of the value.
I'm thinking I have to somehow incorporate the "$" into the for loop, but I'm not sure how to do that.
BODY['html'] += '<br>Total shipped this month:..............Orders........Qty...........Value<br>'
SQL5 = '''
select count(*) as CNT, sum(A.USER_SHIPPED_QTY) as QTY, sum(( A.USER_SHIPPED_QTY) * A.UNIT_PRICE) as VALUE
from SHIPPER_LINE A, SHIPPER B
where B.PACKLIST_ID = A.PACKLIST_ID
and A.CUST_ORDER_ID like ('CO%')
and B.SHIPPED_DATE between ('{}') and ('{}')
'''.format(RP.get_first_of_cur_month_ora(), RP.get_rep_date_ora())
## {} and .format get around the issue of using %s with CO%
print SQL5
curs.execute(SQL5)
for line in curs: ##used to print database lines in HTML
print line
i=0
for c in line:
if i==0:
BODY['html'] += '<pre>' + str(c).rjust(60,' ')
elif i == 1:
BODY['html'] += str(c).rjust(15,' ')
else:
BODY['html'] += str(c).rjust(22,' ') + '</pre>'
i+=1
The "pre" in HTML is used to keep the whitespace and the ' ' after rjust is used to space the numbers properly to go under the column headings. The values that are printed out are generated from the database using the SQL.
Here is what displays in HTML for this code:
Total shipped this month:..............Orders........Qty...........Value
3968 16996 1153525.96
This is what I want it to look like:
Total shipped this month:..............Orders........Qty...........Value
3968 16996 $1153525.96
You could apply the format in the DB by wrapping your sum with a to_char and a currency/numeric format model ...
select to_char(12345.67, 'FML999,999.99') FROM DUAL;
I want to pass the text that comes from this list to see what is contained in it.
The def used is this:
def getTotal(self) :
total = []
for i in range(self.List.getItemCount()) :
total.append(self.List.getItemText(i))
return total
In my main I have this:
msg+=self.getTotal()
What's the correct way of adding to msg so it'll print correctly to the screen?
Expected output:
['Object1', 'Object2']
I'm assuming you're trying to add the list to a string message. In that case you need to use str() to convert the list into a string:
msg += str(self.getTotal())
You can print the objects in the list by doing:
msg += ', '.join(self.getTotal())
I'm not entirely sure what you expect the output to be but would
output_str = ', '.join(self.getTotal())
assumed the list contains numbers I would do it like this:
print msg + ' ' + str(self.getTotal())
If you want to save the whole content in the message first:
msg += ' ' + str(self.getTotal())
print msg
I have this code to print some strings to a text file, but I need python to ignore every empty items, so it doesn't print empty lines.
I wrote this code, which is simple, but should do the trick:
lastReadCategories = open('c:/digitalLibrary/' + connectedUser + '/lastReadCategories.txt', 'w')
for category in lastReadCategoriesList:
if category.split(",")[0] is not "" and category is not None:
lastReadCategories.write(category + '\n')
print(category)
else: print("/" + category + "/")
lastReadCategories.close()
I can see no problem with it, yet, python keeps printing the empty items to the file. All categories are written in this notation: "category,timesRead", that's why I ask python to see if the first string before the comma is not empty. Then I see if the whole item is not empty (is not None). In theory I guess it should work, right?
P.S.: I've already tried asking the if to check if 'category' is not "" and is not " ", still, the same result.
Test for boolean truth instead, and reverse your test so that you are certain that .split() will work in the first place, None.split() would throw an exception:
if category is not None and category.split(",")[0]:
The empty string is 'false-y', there is no need to test it against anything.
You could even just test for:
if category and not category.startswith(','):
for the same end result.
From comments, it appears you have newlines cluttering up your data. Strip those away when testing:
for category in lastReadCategoriesList:
category = category.rstrip('\n')
if category and not category.startswith(','):
lastReadCategories.write(category + '\n')
print(category)
else: print("/{}/".format(category))
Note that you can simply alter category inside the loop; this avoids having to call .rstrip() multiple times.
rstrip() your category before writing it back to file
lastReadCategories = open('c:/digitalLibrary/' + connectedUser +'/lastReadCategories.txt', 'w')
for category in lastReadCategoriesList:
if category.split(",")[0] is not "" and category is not None:
lastReadCategories.write(category.rstrip() + '\n')
print(category.rstrip())
else: print("/" + category + "/")
lastReadCategories.close()
I was able to test it with your sample list provided (without writing it to file):
lastReadCategoriesList = ['A,52', 'B,1\n', 'C,50', ',3']
for category in lastReadCategoriesList:
if category.split(",")[0] is not "" and category is not None:
print(category.rstrip())
else: print("/" + category + "/")
>>> ================================ RESTART ================================
>>>
A,52
B,1
C,50
/,3/
>>>
The classic way to test for an empty string (ie, only whitespace but not '') is with str.strip():
>>> st=' '
>>> bool(st)
True
>>> bool(st.strip())
False
Which also works on a null string:
>>> bool(''.strip())
False
You have if category.split(",")[0] is not "" ... and this is not the recommended way. You can do this:
if category.split(',')[0] and ...
Or, if you want to be wordier:
if bool(category.split(',')[0]) is not False and ...
And you may be dealing with an issue with leading whitespace in the CSV:
>>> ' ,'.split(',')
[' ', '']
>>> ' ,val'.split(',')
[' ', 'val']
I have a list of counters
counters = ['76195087', '963301809', '830123644', '60989448', '0', '0', '76195087', '4006066839', '390361581', '101817210', '0', '0']
and I would like to create a string using some of these counters....
cmd = 'my_command' + counters[0:1]
But I find that I am unable to concatenate strings and lists.
What I must have at the end is a string that looks like this:
my_command 76195087
How do I get these numbers out of their list and get them to behave like strings?
You can join strings in a list with, well, join:
cmd = 'my_command' + ''.join(counters[:1])
But you shouldn't construct a command like that in the first place and give it to os.popen or os.system. Instead, use the subprocess module, which handles the internals (and escapes problematic values):
import subprocess
# You may want to set some options in the following line ...
p = subprocess.Popen(['my_command'] + counters[:1])
p.communicate()
If you just want a single element of the list, just index that element:
cmd = 'my_command ' + counters[0]
If you want to join several elements, use the 'join()' method of strings:
cmd = 'my_command ' + " ".join(counters[0:2]) # add spaces between elements
If you just want to append a single counter, you can use
"my_command " + counters[0]
or
"%s %s" % (command, counters[0])
where command is a variable containing the command as a string. If you want to append more than one counter, ' '.join() is your friend:
>>> ' '.join([command] + counters[:3])
'my_command 76195087 963301809 830123644'
You have to access an element of the list, not sublists of the list, like this:
cmd = 'my_command' + counters[0]
Since I guess you're interested in using all the counters at some point, use a variable to store the index you're currently using, and increment it where you see fit (possibly inside a loop)
idx = 0
cmd1 = 'my_command' + counters[idx]
idx += 1
cmd2 = 'my_command' + counters[idx]
Of course, being careful of not incrementing the index variable beyond the size of the list.