how to convert an int array to string in python - python-3.x

I have a problem in converting an int array into string. Here is my part of code
response_list=[]
for key in json_response['response_code']:
if json_response['response_code'][key] ['0'] is True:
print('No such exist')
response_list.append('Check')
sys.exit()
What happens is this 'response_code' that is part of the output result of my entire code consist of either 0 and 1. So what I want to do is if 'response_code' is 0 in the output result print the needy and exit the whole operation.
I used for but it says 'int is not iterable with for loop. I tried using the dictionary:
response_list=[]
keydict=str(json_response['response_code'])
for key in keydict:
if keydict == ['0'] is True:
print('No such exist')
response_list.append('Check')
sys.exit()
I still get the int is not iterable
TypeError: 'int' object is not iterable
Can someone please explain how to solve the issue
p.s response_list stores the values so I can use later in my code.
What happens in my full code:
I have a list of urls where I want to get it scanned from VirusTotal API. So the API scans the list of urls one by one and if response code = 1 that means API outputs results. If the response code for another url becomes 0 it means API does not show result

You can only use a list for the iteration in For loop as you are using a dict and string doesn't work in you case
Trying to Iterate JSON
for key in json_response['response_code']
Trying to Iterate String
for key in str(json_response['response_code'])
Make sure you are using a valid list for the iteration.
Post your json_response['response_code'] structure if you need any help with the iteration of a specific value in the JSON.
if keydict == ['0'] is True:
This will not work,
If you want to check a variable
if keydict == ['0']: If you want to check for a specific value
if keydict: if you want to check if the keydict has a value

Related

How do I check if a filter returns no results in Python 3?

I have a filter function that I use to clean certain items out of a list:
def filterOutPatternMatches(objList, matchKey, matchPatterns):
def checkPatterns(obj):
delete_it=True
for pat in matchPatterns:
matchString=obj[matchKey]
if pat.search(matchString):
delete_it=False
break
return delete_it
result = filter(checkPatterns, objects);
return result
It works fine, except that there is no easy way for me to find out if the filter() function has returned an empty iterable.
I want to know if the list is empty, and if so, do one thing. If not, do something else.
There are three ways to approach this:
Convert the filter object to a list, then check if it is empty:
l = list(filterObject)
if (len(l) == 0):
# The filterObject is empty, do the empty thing
The problem is that you have to convert the filterObject iterable to a list, which is potentially a very expensive operation if the iterable is very large.
Use next() to pull the first item off of the filter object iterable. If there is nothing in the list, you will get a StopIteration error, which you have to catch.
You will also need to process the first item outside of the rest, since you can't put it back on the iterable.
try:
firstItem = next(filterObject)
# Do whatever you need to do with the first item in the filterObject iterable
except StopIteration:
# Do whatever you do if there are no filter results
for o in filterObject:
# Now handle the rest of the filter results
Problems with this: you have to handle the first item outside of your for loop, which is annoying. If you want to run some aggregation function on the filterObject iterable, you have to deal with the one item that you pulled off separately. Very un-pythonic.
Iterate over the filterObject as you normally would, but set a flag if it is empty:
filterObject = filter(someFunc, someIterable)
itWasEmpty=true
for x in filterObject:
itWasEmpty=false
# Process the filterObject items
if itWasEmpty:
# Do whatever you do if it's empty.
Cons: You need to process the entire list manually. Can't pass the filter object to an aggregation function.
That's all I can come up with!

I'm not getting expected result , I want to know what's wrong with the code

I want to know whether I can use Input function under for loops and Lists?
I'm using the latest version of python 3.7.4.
List=['apple','Pomegranate','orange']
K=print(input('Enter the Value:'))
if (K in List):
print("yes it's in the list")
else:
print("It's not in the list")
If I entered apple I'm getting the result as it's not on the list. I want to know whether we can use Input function under for loops and lists with if-else conditions.
Your issue is with the line
K=print(input('Enter the Value:'))
You do not need print here. Print is a function that takes a value, prints it to your screen and returns None. You passed the input to print, but you want to store the value in K, not print it to the screen (the user is entering the value so they probably do not need to see it again). So change this to:
K=input('Enter the Value:')
Here you can check your error with print function.
List=['apple','Pomegranate','orange']
K=print(input('Enter the Value:'))
print(K)
.....
K is None in this case.

Indexes and ranges in python

I have this code:
def main():
if (len(sys.argv) > 2) :
P=list()
f= open('Trace.txt' , 'w+')
Seed = int(sys.argv[1])
for i in range(2, len(sys.argv)):
P[i-2] = int(sys.argv[i])
for j in range(0, len(sys.argv)-1) :
Probability=P[j]
for Iteration in (K*j, K*(j+1)):
Instruction= generateInstruction(Seed, Probability)
f.write(Instruction)
f.close()
else:
print('Params Error')
if __name__ == "__main__":
main()
The idea is that I am passing some parameters through the command line. the first is seed and the rest I want to have them in a list that I am parsing later and doing treatments according to that parameter.
I keep receiving this error:
P[i-2] = int(sys.argv[i])
IndexError: list assignment index out of range
what am I doing wrong
PS: K, generateSegment() are defined in a previous part of the code.
The error you see is related to a list being indexed with an invalid index.
Specifically, the problem is that P is an empty list at the time is being called in that line so P[0] is indeed not accessible. Perhaps what you want is to actually add the element to the list, this can be achieved, for example, by replacing:
P[i-2] = int(sys.argv[i])
with:
P.append(int(sys.argv[i]))
Note also that argument parsing is typically achieved way more efficiently in Python by using the standard module argparse, rather than parsing sys.argv manually.
It looks like you might be referencing a list item that does not exist.
I haven't used Python in quite a while but I'm pretty sure that if you want to add a value to the end of a list you can use someList.append(foo)
The problem is that you are assigning a value to an index which does not yet exist.
You need to replace
P[i-2] = int(sys.argv[I])
with
P.append(int(sys.argv[i]))
Furthermore, len(sys.argv) will return the number of items in sys.argv however indexing starts at 0 so you need to change:
for i in range(2, len(sys.argv)):
with
for i in range(2, len(sys.argv)-1):
As you will run into a list index out of range error otherwise

How do I replace and update a string multiple times in Python?

I'm working on a quiz program and need some help. I'm trying to replace words one at a time, but Python isn't saving the previously replaced string. Here is a mini example of what I mean:
replacedQuiz=""
easyQuiz = """
You can change a string variable to an integer by typing (__1__)
in front of the variable. It also works vice versa, you can change an
integer
variable to a string by typing (__2__). This is important to remember before
you __3__ strings together, or else a TypeError will occur. While adding an
integer to a string, it is important to separate it using a __4__ (use the
symbol). \n"""
def replaceWord(replaced, quiz, numCount):
if numCount == 1:
replaced = quiz.replace("__1__", "int")
if numCount == 2:
replaced = replaced.replace("__2__", "str")
if numCount == 3:
replaced= replaced.replace("__3__", "concatenate")
if numCount == 4:
replaced= replaced.replace("__4__", ",")
print replaced
def easy():
QCount=1
print easyQuiz
while QCount < 5:
replaceWord(replacedQuiz, easyQuiz, QCount)
QCount += 1
print easy()
I thought that by making a String called replacedQuiz, it would save the first replacement and then I could continue replacing the words inside the quiz and updating it. Please help! I don't know where I'm going wrong
You seem to have made a slight mistake in the scope of your variable replacedQuiz (it'd certainly suggest that you check out some explanation of this topic). Basically, you are replacing replacedQuiz by its new value only within your current function. Your other functions only have access to the global value you defined earlier. There are several ways to fix this (e.g. the global keyword) but the standard way would be to return the new replacedQuiz from your function.
To do so, add the following line to the end of your replaceWord function:
return replacedQuiz
This tells Python to use this value at the line it was called at. You can then define a new value for replacedQuiz within easy by just defining it as the returned value:
replacedQuiz = replaceWord(replacedQuiz, easyQuiz, QCount)

Creating a function that creates two lists in Python 3

I am trying to create a function, getStocks, that gets from the user two lists, one containing the list of stock names and the second containing the list of stock prices. This should be done in a loop such that it keeps on getting a stock name and price until the user enters the string 'done' as a stock name. The function should return both lists. My main issues are figuring out what my parameters are, how to continuously take in the name and price, and what type of loop I should be using. I am very new to programming so any help would be appreciated. I believe I'm close but I am unsure where my errors are.
def getStocks(name,price):
stockNames = []
stockPrices = []
i = 0
name = str(input("What is the name of the stock?"))
price = int(input("what is the price of that stock?"))
while i < len(stockNames):
stockNames.append(name)
stockPrices.append(price)
i += 1
else:
if name = done
return stockNames
return stockPrices
Your question is a bit unclear but some things off the bat, you cant have two return lines, once you hit the first, it leaves the function. Instead you'do write something like
return (stockNames, stockPrices)
Secondly while loops dont have an else, so you'd actually set up your while loop, then setup an if statement at the beginning to check if the string is 'done', then act accordingly. Break will get you out of your last while loop, even though it looks like it's associated with the if. So something like this:
while i < len(stockNames):
if name.upper() == 'DONE':
break
else:
stockNames.append(name)
stockPrices.append(price)
i += 1
Also you have to use == (comparison) instead of = (assignment) when you check your name = done. And dont forget done is a string, so it needs to be in quotations, and I used .upper() to make the input all caps to cover if its lower case or uppercase.
If you can clear up your question a little bit, I can update this answer to include everything put together. I'm not quite understanding why you want to input a list and then also take user input, unless you're appending to that list, at which point you'd want to put the whole thing in a while loop maybe.
Update:
Based on your comment, you could do something like this and enclose the whole thing in a while loop. This takes the incoming two lists (assuming you made a master list somewhere) and sends them both into the getStocks function, where someone can keep appending to the pre-existing list, and then when they type done or DONE or DoNe (doesn't matter since you use .upper() to make the input capitalized) you break out of your while loop and return the updated lists:
def getStocks(name, price):
stockNames = name
stockPrices = price
while 1:
inputName = str(input("What is the name of the stock?"))
inputPrice = int(input("what is the price of that stock?"))
if name.upper() != 'DONE':
stockNames.append(inputName)
stockPrices.append(inputPrice)
else:
break
return (stockNames, stockPrices)
But really, depending on the rest of the structure, you might want to make a dictionary instead of having 2 separate lists, that way everything stays in key:value pairs, so instead of having to check index 0 on both and hoping they didn't get shifted by some rogue function, you'd have the key:value pair of "stock_x":48 always together.

Resources