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
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 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) + ']')
I'm trying to create a simple encryption/decryption code in Python like this (maybe you can see what I'm going for):
def encrypt():
import random
input1 = input('Write Text: ')
input1 = input1.lower()
key = random.randint(10,73)
output = []
for character in input1:
number = ord(character) - 96
number = number + key
output.append(number)
output.insert(0,key)
print (''.join(map(str, output)))
def decrypt():
text = input ('What to decrypt?')
key = int(text[0:2])
text = text[2:]
n=2
text = text
text = [text[i:i+n] for i in range(0, len(text), n)]
text = map(int,text)
text = [x - key for x in text]
text = ''.join(map(str,text))
text = int(text)
print (text)
for character in str(text):
output = []
character = int((character+96))
number = str(chr(character))
output.append(number)
print (''.join(map(str, output)))
When I run the decryptor with the output from the encryption output, I get "TypeError: Can't convert 'int' object to str implicitly."
As you can see, I've added some redundancies to help try to fix things but nothing's working. I ran it with different code (can't remember what), but all that one kept outputting was something like "generatorobject at ."
I'm really lost and I could use some pointers guys, please and thank you.
EDIT: The problem arises on line 27.
EDIT 2: Replaced "character = int((character+96))" with "character = int(character)+96", now the problem is that it only prints (and as I can only assume) only appends the last letter of the decrypted message.
EDIT 2 SOLVED: output = [] was in the for loop, thus resetting it every time. Problem solved, thank you everyone!
Full traceback would help, but it looks like character = int(character)+96 is what you want on line 27.
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'm writing a python program. The program calculates Latin Squares using two numbers the user enters on a previous page. But but an error keeps coming up, "cannot concatenate 'str' and 'list' objects" here is the program:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# enable debugging
import cgi
import cgitb
cgitb.enable()
def template(file, **vars):
return open(file, 'r').read() % vars
print "Content-type: text/html\n"
print
form = cgi.FieldStorage() # instantiate only once!
num_1 = form.getfirst('num_1')
num_2 = form.getfirst('num_2')
int1r = str(num_1)
int2r = str(num_2)
def calc_range(int2r, int1r):
start = range(int2r, int1r + 1)
end = range(1, int2r)
return start+end
int1 = int(int1r)
int2 = int(int2r)
out_str = ''
for i in range(0, int1):
first_line_num = (int2 + i) % int1
if first_line_num == 0:
first_line_num = int1
line = calc_range(first_line_num, int1)
out_str += line
print template('results.html', output=out_str, title="Latin Squares")
range returns a list object, so when you say
line = calc_range(first_line_num, int1)
You are assigning a list to line. This is why out_str += line throws the error.
You can use str() to convert a list to a string, or you can build up a string a different way to get the results you are looking for.
By doing out_str += line, you're trying to add a list (from calc_range) to a string. I don't even know what this is supposed to be doing, but that's where the problem lies.
You didn't say what line you're getting the error from, but I'm guessing it's:
out_str += line
The first variable is a string. The second is a list of numbers. You can't concatenate a list onto a string. I don't know what you're trying to do exactly, but how about:
out_str += ", ".join(line)
That will add the numbers joined by commas onto out_str.
calc_range() returns a list; however, you are attempting to add it to a string (out_str).
It looks like your code is unfinished - don't you want to do something with the range of numbers returned by calc_range()? Like, say, something with the form?
line = ''.join(num_1[index] for index in calc_range(first_line_num, int1))
I don't know if that's what you want - but maybe something like that?